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.
data/lib/nexo/workflow.rb CHANGED
@@ -47,7 +47,7 @@ module Nexo
47
47
  # (pending approval call — Spec 16), and `"__buffer_events__"` (the persisted
48
48
  # buffering choice — Spec 5). ::cleared_state strips these when a run reaches
49
49
  # `"done"`; #checkpoint_all refuses a step named after any of them (Spec 21).
50
- RESERVED_STATE_KEYS = %w[__suspend__ __approval__ __buffer_events__].freeze
50
+ RESERVED_STATE_KEYS = %w[__suspend__ __approval__ __approvals__ __buffer_events__].freeze
51
51
 
52
52
  # Control-flow signal raised by #suspend! and caught by ::execute to pause
53
53
  # a run durably — NOT a failure. It transitions the run to `"suspended"`
@@ -304,7 +304,14 @@ module Nexo
304
304
 
305
305
  instance = new(run, buffer_events: buffer_events)
306
306
  instance.instance_variable_set(:@resume_input, resume_input)
307
- result = instance.call(payload)
307
+ # Run inside ruby_llm's workflow context so every model request, tool call
308
+ # and usage record made by this run carries the run id (and, in Rails,
309
+ # lands in `ruby_llm_usages` with it). Instrumentation only: it changes no
310
+ # outcome, and Suspended or a failure pass straight through it.
311
+ result = ::RubyLLM.workflow(name || "Nexo::Workflow", id: run.id) do |trace|
312
+ instance.instance_variable_set(:@trace, trace)
313
+ instance.call(payload)
314
+ end
308
315
  run.update!(status: "done", result: stringify_keys(result), **cleared_state(run))
309
316
  notify_status(run)
310
317
  run
@@ -479,7 +486,7 @@ module Nexo
479
486
  # or is reloaded from the AR json column on a cross-process resume — and so
480
487
  # the first pass and the resume pass see identical data. Values must be
481
488
  # json-serializable (documented above).
482
- value = json_normalize(yield)
489
+ value = json_normalize(traced(key) { yield })
483
490
  @run.state = store.merge(key => value)
484
491
  @run.save_state! if @run.respond_to?(:save_state!)
485
492
  value
@@ -535,7 +542,7 @@ module Nexo
535
542
 
536
543
  unless pending.empty?
537
544
  Nexo.concurrent(max_in_flight: pending.size) do |c|
538
- pending.each { |name, callable| c.add { persist_checkpoint(name, callable.call) } }
545
+ pending.each { |name, callable| c.add { persist_checkpoint(name, traced(name.to_s) { callable.call }) } }
539
546
  end
540
547
  end
541
548
 
@@ -793,22 +800,28 @@ module Nexo
793
800
  # (sandbox), the agent owns the *what* (permissions) and *how* (skills). Driving
794
801
  # an agent never widens its authority; its safe default (`:read_only`) is
795
802
  # untouched. Raises ConfigurationError when no `agent` is declared.
796
- # Durable approval (Spec 16): when the driven agent runs under an `:approve`
797
- # permission gate and hits a sensitive capability with no decision yet, the
798
- # gate raises Nexo::ApprovalRequired, which propagates out of the `ruby_llm`
799
- # tool loop (Group 0: the loop does not rescue tool exceptions) and out of
803
+ # Durable approval (Spec 16, per call since 0.14): when the driven agent runs
804
+ # under an `:approve` permission gate and reaches a gated call nobody has
805
+ # decided, the gate raises Nexo::ApprovalRequired, which propagates out of the
806
+ # `ruby_llm` tool loop (the loop does not rescue tool exceptions) and out of
800
807
  # Agent#prompt. `run_agent` rescues it, records the pending call under the
801
808
  # reserved `"__approval__"` state key, and #suspend!s the run — so the worker
802
- # returns and a host renders "approval pending" from `run.state`. On
803
- # ::resume/::resume_later with `{approved: …}` the decision is threaded into
804
- # the agent (via `decision:`), so the same gate now allows (→ run completes) or
805
- # denies (→ the tool returns `{error:}`, the model adapts, run still completes).
809
+ # returns and a host renders "approval pending" from `run.state`.
810
+ #
811
+ # ::resume/::resume_later with `{approved: …}` answers THAT call: the answer
812
+ # is filed under the call's key in the reserved `"__approvals__"` state key,
813
+ # and every answer recorded so far is handed to the agent. The re-driven agent
814
+ # then runs the approved call, gets `{error:}` for a declined one, and
815
+ # suspends again at any gated call that has no answer yet — approving one
816
+ # write never approves the next.
806
817
  def run_agent(prompt, max_turns: 25)
807
818
  klass = self.class.agent or raise Nexo::ConfigurationError,
808
819
  "#{self.class} has no `agent` declared; add `agent MyAgent`"
809
- agent = klass.new(sandbox: sandbox, **agent_decision_kwargs)
810
- agent.prompt(prompt, max_turns: max_turns) do |type, payload|
811
- emit(:"agent_#{type}", serializable(type, payload))
820
+ agent = klass.new(sandbox: sandbox, decisions: record_approval!)
821
+ traced(klass.name || "agent") do
822
+ agent.prompt(prompt, max_turns: max_turns) do |type, payload|
823
+ emit(:"agent_#{type}", serializable(type, payload))
824
+ end
812
825
  end
813
826
  rescue Nexo::ApprovalRequired => a
814
827
  # Persist the pending call (immediately, like a checkpoint) so a host can
@@ -839,16 +852,35 @@ module Nexo
839
852
 
840
853
  private
841
854
 
842
- # The `decision:` kwargs handed to the agent built in #run_agent (Spec 16).
843
- # A decision is produced ONLY when the resume input actually carries an
844
- # `:approved` key — so a data-only resume (e.g. `resume(id, doc_id: 42)` for
845
- # a `suspend!` that was waiting on data, not approval) does NOT fabricate an
846
- # `{approved: false}` denial that would silently refuse a later `:approve`
847
- # gate. Undecided ⇒ `{}` ⇒ the gate suspends and asks a human. Never widens
848
- # authority — it only answers an already-`:approve` gate.
849
- def agent_decision_kwargs
850
- d = resume_input
851
- d.key?(:approved) ? {decision: {approved: !!d[:approved]}} : {}
855
+ # Runs the block as a named step of this run's ruby_llm workflow context, so
856
+ # the events inside it are attributed to that step (a checkpoint, an agent).
857
+ # A plain `yield` when the instance is driven outside ::execute.
858
+ def traced(name, &block)
859
+ @trace ? @trace.step(name, &block) : yield
860
+ end
861
+
862
+ # Files the resume input's `:approved` answer under the pending call's key and
863
+ # returns every approval recorded on this run (a Hash of
864
+ # Permissions::approval_key → `true`/`false`).
865
+ #
866
+ # An answer is recorded ONLY when the resume input carries an `:approved` key
867
+ # AND a call is actually pending — so a data-only resume
868
+ # (`resume(id, doc_id: 42)` for a `suspend!` that was waiting on data) records
869
+ # nothing, and an `approved:` with no pending call approves nothing. The
870
+ # pending entry is cleared once answered, so re-entering #run_agent in the
871
+ # same pass cannot file the answer twice. Never widens authority — it only
872
+ # answers an already-`:approve` gate, one call at a time.
873
+ def record_approval!
874
+ state = @run.state || {}
875
+ approvals = state["__approvals__"] || {}
876
+ pending = state["__approval__"]
877
+ return approvals unless pending && resume_input.key?(:approved)
878
+
879
+ key = Permissions.approval_key(pending["capability"], pending["tool"], pending["args"])
880
+ approvals = approvals.merge(key => !!resume_input[:approved])
881
+ @run.state = state.except("__approval__").merge("__approvals__" => approvals)
882
+ @run.save_state! if @run.respond_to?(:save_state!)
883
+ approvals
852
884
  end
853
885
 
854
886
  # Persists ONE completed #checkpoint_all step (Spec 21) — json_normalizes the
data/lib/nexo.rb CHANGED
@@ -52,6 +52,9 @@ module Nexo
52
52
  # and the tool `args` — enough for a host to render the approval prompt.
53
53
  attr_reader :capability, :detail, :args
54
54
 
55
+ # The key this call is decided under — see Permissions::approval_key.
56
+ def key = Permissions.approval_key(capability, detail, args)
57
+
55
58
  # Builds the signal for `capability` acting on `detail` with `args`; the
56
59
  # message reads "approval required for <capability> (<detail>)".
57
60
  def initialize(capability, detail = nil, args = nil)
@@ -62,6 +65,9 @@ module Nexo
62
65
  end
63
66
  end
64
67
 
68
+ @undeclared_tools = Set.new
69
+ @undeclared_tools_lock = Mutex.new
70
+
65
71
  class << self
66
72
  # Yields the singleton Configuration for in-place setup and returns it.
67
73
  #
@@ -84,6 +90,20 @@ module Nexo
84
90
  @config = Configuration.new
85
91
  end
86
92
 
93
+ # Warns, once per tool name, that the model called a tool Nexo did not attach
94
+ # (see Configuration#strict_tools). Called from the tool backstop, possibly on
95
+ # several tool threads at once, hence the lock.
96
+ def warn_undeclared_tool(name, agent_class)
97
+ @undeclared_tools_lock.synchronize do
98
+ return if @undeclared_tools.include?(name)
99
+
100
+ @undeclared_tools << name
101
+ end
102
+ warn "[nexo] #{agent_class} ran the tool `#{name}`, which was added to the chat outside " \
103
+ "the `tools` macro, so no permission gate saw the call. Declare it with `tools` " \
104
+ "(optionally `capability:`); Nexo.config.strict_tools = true refuses such calls."
105
+ end
106
+
87
107
  # Returns a fresh run id as a time-ordered UUID v7 string (Ruby 3.3+).
88
108
  # Both run stores and the WorkflowRun model obtain ids only through this
89
109
  # helper, keeping id shape identical across backends.
data/sig/nexo/agent.rbs CHANGED
@@ -7,6 +7,7 @@ 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.tools: (*untyped list, ?capability: Symbol?) -> Array[Hash[Symbol, untyped]]
10
11
 
11
12
  attr_reader cwd: String
12
13
  attr_reader model: untyped
@@ -16,7 +17,8 @@ module Nexo
16
17
  attr_reader permissions: Permissions
17
18
  attr_reader instructions: String?
18
19
 
19
- def initialize: (?cwd: String, ?model: untyped, ?sandbox: untyped, ?permissions: untyped) -> void
20
+ def initialize: (?cwd: String, ?model: untyped, ?sandbox: untyped, ?permissions: untyped,
21
+ ?decision: Hash[Symbol, bool]?, ?decisions: Hash[String, bool]?, ?loop: untyped) -> void
20
22
  def chat: (?base: untyped) -> RubyLLM::Chat
21
23
  def prompt: (String text) ?{ (untyped) -> void } -> untyped
22
24
  end
@@ -8,7 +8,19 @@ module Nexo
8
8
  type capability = Symbol
9
9
  type ask_hook = ^(capability, untyped) -> boolish
10
10
 
11
- def initialize: (?mode: Symbol, ?allow: Array[Symbol], ?mcp_allow: Array[untyped], ?on_ask: ask_hook?, ?ask_when: ask_hook?) -> void
11
+ attr_reader mode: Symbol
12
+ attr_reader decisions: Hash[String, bool]?
13
+ attr_accessor decision: Hash[Symbol, bool]?
14
+
15
+ def self.approval_key: (untyped capability, untyped detail, ?untyped args) -> String
16
+
17
+ def initialize: (?mode: Symbol, ?allow: Array[Symbol], ?mcp_allow: Array[untyped], ?on_ask: ask_hook?,
18
+ ?ask_when: ask_hook?, ?approve_when: ask_hook?, ?decision: Hash[Symbol, bool]?,
19
+ ?decisions: Hash[untyped, bool]?) -> void
20
+ def with_decision: (Hash[Symbol, bool]? decision) -> Permissions
21
+ def with_decisions: (Hash[untyped, bool]? decisions) -> Permissions
22
+ def never_allows?: (capability capability) -> bool
23
+ def never_allows_mcp?: (untyped tool_name) -> bool
12
24
  def authorize_mcp!: (untyped tool_name, ?untyped args) -> bool
13
25
  def authorize!: (capability capability, ?untyped detail) -> bool
14
26
  end
data/sig/nexo/sandbox.rbs CHANGED
@@ -8,5 +8,6 @@ module Nexo
8
8
  def instructions: () -> String?
9
9
  def supports?: (Symbol capability) -> bool
10
10
  def mtime: (String path) -> Time?
11
+ def hardening_gaps: () -> Array[String]
11
12
  end
12
13
  end
@@ -3,7 +3,12 @@ module Nexo
3
3
  class Local < Sandbox
4
4
  attr_reader cwd: String
5
5
 
6
- def initialize: (?cwd: String, ?env: Hash[String, String]) -> void
6
+ attr_reader isolation: untyped
7
+
8
+ def initialize: (?cwd: String, ?env: Hash[untyped, String], ?isolation: untyped, ?readable: Array[String]) -> void
9
+ def confined?: () -> bool
10
+ def hardening_gaps: () -> Array[String]
11
+ def shell: (String command, ?timeout: Numeric) -> Hash[Symbol, untyped]
7
12
  def instructions: () -> String
8
13
  def supports?: (Symbol cap) -> bool
9
14
  def mtime: (String path) -> Time?
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.13.0
4
+ version: 0.14.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mario Alberto Chávez
@@ -155,6 +155,7 @@ files:
155
155
  - lib/nexo/concurrent.rb
156
156
  - lib/nexo/configuration.rb
157
157
  - lib/nexo/engine.rb
158
+ - lib/nexo/gated_tool.rb
158
159
  - lib/nexo/loop.rb
159
160
  - lib/nexo/loops/ruby_llm.rb
160
161
  - lib/nexo/mcp.rb