nexo_ai 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +110 -0
  3. data/docs/durable-workflows.md +26 -15
  4. data/docs/loops.md +8 -5
  5. data/docs/mcp.md +4 -2
  6. data/docs/skills.md +18 -6
  7. data/docs/tools.md +35 -3
  8. data/docs/workflows.md +2 -2
  9. data/examples/README.md +63 -30
  10. data/examples/approval_agent.rb +21 -7
  11. data/examples/artifact_from_template.rb +1 -1
  12. data/examples/chat_session.rb +2 -1
  13. data/examples/code_reviewer.rb +4 -3
  14. data/examples/company_brain.rb +54 -0
  15. data/examples/confined_shell.rb +56 -0
  16. data/examples/container_review.rb +3 -2
  17. data/examples/data_analyst.rb +90 -0
  18. data/examples/deferred_tools.rb +57 -0
  19. data/examples/inbox_digest_task.rb +47 -21
  20. data/examples/llm_options.rb +56 -0
  21. data/examples/marketing_team.rb +85 -0
  22. data/examples/mcp_filesystem.rb +11 -6
  23. data/examples/multiple_approvals.rb +56 -0
  24. data/examples/news_search.rb +20 -11
  25. data/examples/news_summary.rb +4 -3
  26. data/examples/retry_and_cancel.rb +81 -0
  27. data/examples/skills/email-triage/SKILL.md +44 -0
  28. data/examples/skills/{news_summary → news-summary}/SKILL.md +1 -1
  29. data/examples/skills/refunds/SKILL.md +24 -0
  30. data/examples/software_factory.rb +127 -0
  31. data/examples/support/handbook/expenses.md +6 -0
  32. data/examples/support/handbook/on-call.md +5 -0
  33. data/examples/support/handbook/time-off.md +6 -0
  34. data/examples/support/handbook_server.rb +46 -0
  35. data/examples/support/model.rb +33 -0
  36. data/examples/support_agent.rb +102 -0
  37. data/examples/tool_question.rb +59 -0
  38. data/examples/usage_report.rb +50 -0
  39. data/lib/generators/nexo/skill/skill_generator.rb +7 -1
  40. data/lib/generators/nexo/skill/templates/SKILL.md.tt +1 -1
  41. data/lib/nexo/agent.rb +86 -10
  42. data/lib/nexo/approvable.rb +5 -1
  43. data/lib/nexo/gated_tool.rb +9 -1
  44. data/lib/nexo/loops/ruby_llm.rb +86 -10
  45. data/lib/nexo/model_options.rb +2 -2
  46. data/lib/nexo/permissions.rb +27 -1
  47. data/lib/nexo/run_store.rb +11 -4
  48. data/lib/nexo/sandbox.rb +9 -0
  49. data/lib/nexo/sandbox_file_store.rb +14 -5
  50. data/lib/nexo/sandboxes/container.rb +16 -1
  51. data/lib/nexo/sandboxes/local.rb +11 -0
  52. data/lib/nexo/sandboxes/virtual.rb +5 -0
  53. data/lib/nexo/skills/skill.rb +70 -33
  54. data/lib/nexo/skills.rb +10 -1
  55. data/lib/nexo/version.rb +1 -1
  56. data/lib/nexo/workflow.rb +77 -25
  57. data/lib/nexo.rb +10 -0
  58. data/sig/nexo/agent.rbs +5 -2
  59. data/sig/nexo/permissions.rbs +3 -0
  60. data/sig/nexo/sandbox.rbs +2 -0
  61. metadata +21 -5
  62. data/examples/inbox_digest.rb +0 -62
  63. data/examples/inbox_digest_http.rb +0 -69
  64. data/examples/skills/email_triage/SKILL.md +0 -47
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The local shell inside an OS sandbox: a command can write only in the working
4
+ # directory, cannot read your home directory, and has no network. No model.
5
+ #
6
+ # ruby -Ilib examples/confined_shell.rb
7
+ #
8
+ # Needs the `mxc` gem and an OS it supports (Seatbelt on macOS, Bubblewrap on
9
+ # Linux). The file tools of a `:local` sandbox were always fenced to the working
10
+ # directory; a shell command is a process on your machine, and this is what
11
+ # fences it too.
12
+ require "nexo"
13
+ require "tmpdir"
14
+
15
+ def run(sandbox, label, command)
16
+ out = sandbox.shell(command)
17
+ result = (out[:status].zero? ? "ok" : "refused").ljust(8)
18
+ puts " #{result}#{label.ljust(30)} #{(out[:stdout] + out[:stderr]).strip.lines.first.to_s.strip[0, 60]}"
19
+ end
20
+
21
+ if __FILE__ == $PROGRAM_NAME
22
+ Dir.mktmpdir("nexo-confined") do |dir|
23
+ workspace = File.realpath(dir)
24
+ secret = File.join(Dir.home, ".nexo-example-secret")
25
+ File.write(secret, "TOP SECRET")
26
+
27
+ begin
28
+ # `readable: :ruby` grants the running Ruby's install and gem paths, which a
29
+ # Ruby under your home directory needs in order to start.
30
+ confined = Nexo::Sandboxes::Local.new(cwd: workspace, isolation: :confined, readable: :ruby)
31
+ confined.shell("true") # a machine that cannot confine raises here
32
+ rescue Nexo::ConfigurationError, Nexo::MissingDependencyError => e
33
+ File.delete(secret)
34
+ abort "this machine cannot confine a shell: #{e.message}"
35
+ end
36
+
37
+ open_shell = Nexo::Sandboxes::Local.new(cwd: workspace)
38
+ commands = {
39
+ "write inside the workspace" => "echo made > made.txt && cat made.txt",
40
+ "run a Ruby script" => %(#{RbConfig.ruby} -e 'require "json"; puts JSON.generate(ok: true)'),
41
+ "read a file in your home" => "cat #{secret}",
42
+ "write outside the workspace" => "touch #{File.join(Dir.home, ".nexo-example-escape")}",
43
+ "reach the network" => "curl -s -m 3 -o /dev/null https://example.com && echo reached"
44
+ }
45
+
46
+ puts "isolation: :confined"
47
+ commands.each { |label, command| run(confined, label, command) }
48
+ puts "what it does not contain: #{confined.hardening_gaps.inspect}"
49
+
50
+ puts "\nno isolation (the default :local shell)"
51
+ commands.each { |label, command| run(open_shell, label, command) }
52
+ puts "what it does not contain: #{open_shell.hardening_gaps.inspect}"
53
+ ensure
54
+ [secret, File.join(Dir.home, ".nexo-example-escape")].each { |path| File.delete(path) if File.exist?(path) }
55
+ end
56
+ end
@@ -9,14 +9,15 @@
9
9
  # ephemeral writable scratch at /workspace, and the host repo bind-mounted
10
10
  # READ-ONLY. When the run ends, `agent.close` tears the container down.
11
11
  #
12
- # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b ruby -Ilib examples/container_review.rb /path/to/repo
12
+ # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b NEXO_PROVIDER=ollama ruby -Ilib examples/container_review.rb /path/to/repo
13
13
  #
14
14
  # Point at Apple's runtime on a Mac by setting NEXO_CONTAINER_RUNTIME=apple.
15
15
  # Nothing here is provider-specific: NEXO_MODEL takes any ruby_llm-supported model.
16
16
  require "nexo"
17
+ require_relative "support/model"
17
18
 
18
19
  class ContainerReviewer < Nexo::Agent
19
- model ENV.fetch("NEXO_MODEL") # provider-neutral; e.g. gemma3:12b via Ollama
20
+ Examples.model(self) # NEXO_MODEL, plus NEXO_PROVIDER=ollama for a local model
20
21
  permissions :read_only # safe default
21
22
 
22
23
  instructions <<~PROMPT
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ # A data analyst: it answers questions by running SQL, reads freely, and has to
4
+ # ask before it changes anything. (After Eve's "Data agent" template.)
5
+ #
6
+ # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b NEXO_PROVIDER=ollama ruby -Ilib examples/data_analyst.rb
7
+ #
8
+ # Needs the `sqlite3` command. Two tools, two capabilities:
9
+ #
10
+ # * `QuerySql` is `:read`. It opens the database read-only, so the guarantee is
11
+ # the database's, not a guess about what the SQL does.
12
+ # * `ExecuteSql` is `:write`. Under `:ask` every call is put to `on_ask` — here a
13
+ # hook that prints the statement and refuses unless NEXO_APPROVE=1.
14
+ #
15
+ # `:ask` is the synchronous sibling of `:approve`: right when a person is at the
16
+ # keyboard while the agent runs.
17
+ require "nexo"
18
+ require "tmpdir"
19
+ require_relative "support/model"
20
+
21
+ DATABASE = File.join(Dir.mktmpdir("nexo-analyst"), "shop.db")
22
+
23
+ def sqlite(*arguments, sql)
24
+ out, err, status = Nexo::Sandboxes::Subprocess.capture({"PATH" => ENV["PATH"]}, "sqlite3", *arguments, DATABASE, sql, timeout: 10)
25
+ (status == 0) ? out : {error: err.strip}
26
+ rescue Timeout::Error => e
27
+ {error: e.message}
28
+ end
29
+
30
+ class DescribeTables < RubyLLM::Tool
31
+ description "Lists the tables in the database with their columns."
32
+
33
+ def execute = sqlite("-readonly", "SELECT name, sql FROM sqlite_master WHERE type = 'table'")
34
+ end
35
+
36
+ class QuerySql < RubyLLM::Tool
37
+ description "Runs one read-only SQL query and returns the rows, with a header line."
38
+ parameter :sql, type: :string, description: "A SELECT statement"
39
+
40
+ def execute(sql:) = sqlite("-readonly", "-header", sql)
41
+ end
42
+
43
+ class ExecuteSql < RubyLLM::Tool
44
+ description "Runs one SQL statement that changes data (INSERT, UPDATE, DELETE)."
45
+ parameter :sql, type: :string, description: "The statement"
46
+
47
+ def execute(sql:)
48
+ result = sqlite(sql)
49
+ result.is_a?(Hash) ? result : "Done."
50
+ end
51
+ end
52
+
53
+ class Analyst < Nexo::Agent
54
+ Examples.model(self)
55
+ file_tools :none
56
+ permissions Nexo::Permissions.new(
57
+ mode: :ask,
58
+ on_ask: lambda { |capability, detail|
59
+ approved = ENV["NEXO_APPROVE"] == "1"
60
+ puts " [asked] #{capability}: #{detail} -> #{approved ? "approved" : "refused (set NEXO_APPROVE=1 to allow)"}"
61
+ approved
62
+ }
63
+ )
64
+ tools DescribeTables, QuerySql, capability: :read
65
+ tools ExecuteSql, capability: :write
66
+
67
+ instructions "You are a data analyst. Look at the tables before you query. Answer with the numbers you found. " \
68
+ "If a change is refused, say so and do not try another way."
69
+ end
70
+
71
+ if __FILE__ == $PROGRAM_NAME
72
+ abort "set NEXO_LIVE=1 to run this live example" unless ENV["NEXO_LIVE"]
73
+ abort "this example needs the sqlite3 command" unless system("command -v sqlite3 > /dev/null 2>&1")
74
+
75
+ sqlite(<<~SQL)
76
+ CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, test INTEGER DEFAULT 0);
77
+ CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, total REAL);
78
+ INSERT INTO customers VALUES (1, 'Ada', 0), (2, 'Grace', 0), (3, 'QA Bot', 1);
79
+ INSERT INTO orders VALUES (1, 1, 120.0), (2, 1, 80.5), (3, 2, 310.0), (4, 3, 9999.0);
80
+ SQL
81
+
82
+ agent = Analyst.new
83
+ puts "== A question: reads only =="
84
+ puts agent.prompt("Which real (non-test) customer has spent the most, and how much?").content
85
+
86
+ puts "\n== A change: it has to ask =="
87
+ puts agent.prompt("Delete the orders that belong to test customers.").content
88
+
89
+ puts "\norders left: #{sqlite("-readonly", "SELECT COUNT(*) FROM orders").to_s.strip}"
90
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Deferred tools: a long catalogue kept out of the model's context until the
4
+ # model looks for the tool it needs.
5
+ #
6
+ # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b NEXO_PROVIDER=ollama ruby -Ilib examples/deferred_tools.rb
7
+ #
8
+ # Every tool definition sent with a request costs context. With `defer: true`
9
+ # a tool's definition is held back; the model finds it through tool search (the
10
+ # provider's own where it has one, ruby_llm's `tool_search` tool otherwise) and
11
+ # only then is it sent. Deferring changes what the model is told up front, not
12
+ # what it may do: a deferred tool is gated like any other.
13
+ require "nexo"
14
+ require_relative "support/model"
15
+
16
+ module Catalog
17
+ # Six small lookups standing in for a catalogue of dozens.
18
+ FACTS = {
19
+ "StockLevel" => ["Returns how many units of a SKU are in the warehouse", :sku, ->(v) { "#{v}: 42 units" }],
20
+ "ShippingQuote" => ["Returns the cost to ship a parcel to a country", :country, ->(v) { "#{v}: $18.50" }],
21
+ "ExchangeRate" => ["Returns today's exchange rate for a currency against USD", :currency, ->(v) { "1 USD = 17.2 #{v}" }],
22
+ "Holiday" => ["Returns the next public holiday in a country", :country, ->(v) { "#{v}: December 25" }],
23
+ "Weather" => ["Returns the weather in a city", :city, ->(v) { "#{v}: sunny, 24C" }],
24
+ "OfficeHours" => ["Returns the opening hours of an office", :office, ->(v) { "#{v}: 9:00 to 18:00" }]
25
+ }.freeze
26
+
27
+ FACTS.each do |name, (text, argument, answer)|
28
+ const_set(name, Class.new(RubyLLM::Tool) do
29
+ description text
30
+ parameter argument, type: :string, description: "The #{argument}"
31
+ define_method(:execute) { |**arguments| answer.call(arguments.fetch(argument)) }
32
+ end)
33
+ end
34
+
35
+ def self.tools = FACTS.keys.map { |name| const_get(name) }
36
+ end
37
+
38
+ class Operations < Nexo::Agent
39
+ Examples.model(self)
40
+ tools(*Catalog.tools, defer: true)
41
+ instructions "Answer from your tools. If you do not see a tool for the job, search for one."
42
+ end
43
+
44
+ if __FILE__ == $PROGRAM_NAME
45
+ abort "set NEXO_LIVE=1 to run this live example" unless ENV["NEXO_LIVE"]
46
+
47
+ agent = Operations.new
48
+ chat = agent.chat
49
+ puts "deferred (held back): #{chat.deferred_tools.keys.size} tools"
50
+
51
+ calls = []
52
+ response = agent.prompt("How many units of SKU A-17 are in the warehouse?") do |type, payload|
53
+ calls << payload.name.to_s if type == :tool_call
54
+ end
55
+ puts "calls: #{calls.inspect}"
56
+ puts "answer: #{response.content}"
57
+ end
@@ -1,40 +1,66 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Verification example — Spec 8 (Workflow↔Agent glue). The inbox digest as a TASK.
3
+ # A Task: a workflow that drives an agent (`agent` macro + `run_agent`) over
4
+ # files staged into the run's sandbox, and keeps the result as a named artifact.
4
5
  #
5
- # Wraps the Spec 6 InboxTriage agent (Gmail MCP + email_triage skill, read-only + gated)
6
- # in a Workflow that runs it and captures the digest as a named artifact. The SAME workflow
7
- # is a scheduled Task (call it from ActiveJob/cron) or an interactive Action (call it from a
8
- # controller after staging uploads) — no code difference.
6
+ # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b NEXO_PROVIDER=ollama ruby -Ilib examples/inbox_digest_task.rb
9
7
  #
10
- # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b ruby -Ilib examples/inbox_digest_task.rb
11
- #
12
- # Requires the Spec 6 InboxTriage agent (examples/inbox_digest.rb) and its email_triage skill.
8
+ # The mail here is three files, so the example runs with nothing but a model.
9
+ # The same shape holds when the mail comes from an MCP server: declare `mcp` and
10
+ # `mcp_allow` on the agent and drop the staging.
13
11
  require "nexo"
14
- require_relative "inbox_digest" # defines InboxTriage (Gmail MCP + skill, read-only)
12
+ require_relative "support/model"
13
+
14
+ Nexo.configure { |c| c.skills_path = File.expand_path("skills", __dir__) }
15
+
16
+ class InboxTriage < Nexo::Agent
17
+ Examples.model(self)
18
+ permissions :read_only # it can list and read the staged mail, and nothing else
19
+ skills "email-triage" # the rules live in examples/skills/email-triage/SKILL.md
20
+
21
+ instructions "You triage the mail in the inbox/ folder of your workspace, following the email-triage skill."
22
+ end
15
23
 
16
24
  class InboxDigestTask < Nexo::Workflow
17
- agent InboxTriage # Spec 8: this workflow drives that agent, sharing the run sandbox
25
+ agent InboxTriage # this workflow drives that agent, which shares the run's sandbox
18
26
 
19
27
  def call(payload)
20
- window = payload[:window] || "newer_than:1d"
21
- response = run_agent("Triage #{window} and produce the markdown digest per the skill.")
22
- # Spec 7: capture the agent's output as a retrievable artifact.
28
+ stage(payload[:mail]) # the workflow puts the mail in the sandbox; the agent only reads
29
+ response = run_agent("Read every file under inbox/ and produce the markdown digest per the skill.")
23
30
  artifact("inbox-digest.md", content: response.content)
24
- {window: window}
31
+ {messages: payload[:mail].size}
25
32
  end
26
33
  end
27
34
 
35
+ MAIL = {
36
+ "inbox/01-landlord.txt" => <<~MAIL,
37
+ From: Building Management <office@riverside.example>
38
+ Subject: Water shut-off Thursday 9-11am
39
+ The water will be off on Thursday morning for valve work. Reply by Wednesday if
40
+ you need access to the basement storage that day.
41
+ MAIL
42
+ "inbox/02-newsletter.txt" => <<~MAIL,
43
+ From: Ruby Weekly <news@rubyweekly.example>
44
+ Subject: Issue 742
45
+ This week: a new minor release, three conference talks, and a gem of the week.
46
+ MAIL
47
+ "inbox/03-invoice.txt" => <<~MAIL
48
+ From: Acme Hosting <billing@acme.example>
49
+ Subject: Invoice 2291 is due on the 30th
50
+ Your invoice for November ($48.00) is due on November 30. No action is needed if
51
+ autopay is on; it is currently OFF on this account.
52
+ MAIL
53
+ }.freeze
54
+
28
55
  if __FILE__ == $PROGRAM_NAME
29
56
  abort "set NEXO_LIVE=1 to run this live example" unless ENV["NEXO_LIVE"]
30
57
 
31
- run = InboxDigestTask.run(window: "newer_than:1d")
58
+ run = InboxDigestTask.run(mail: MAIL)
32
59
  puts "run #{run.id} -> #{run.status}"
33
- art = run.artifacts.find { |a| (a["name"] || a[:name]) == "inbox-digest.md" }
34
- puts(art && (art["content"] || art[:content]))
60
+ digest = run.artifacts.find { |artifact| artifact["name"] == "inbox-digest.md" }
61
+ puts Nexo::Workflow.artifact_body(digest)
35
62
 
36
- # As a scheduled Task, a host app would do (in an ActiveJob):
37
- # InboxDigestTask.run(window: "newer_than:1d")
38
- # As an interactive Action, a controller would stage uploads first, then the same run.
39
- # Scheduling itself lives in the host (cron / GoodJob / whenever) — Nexo stays schedulable.
63
+ # As a scheduled Task, a host app runs the same line from a job:
64
+ # InboxDigestTask.run(mail: fetch_mail)
65
+ # Scheduling itself lives in the host (cron, Solid Queue, GoodJob).
40
66
  end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The `llm` block: ruby_llm's own agent options on a Nexo agent — here a
4
+ # fallback model, a temperature and a context budget.
5
+ #
6
+ # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b NEXO_PROVIDER=ollama ruby -Ilib examples/llm_options.rb
7
+ #
8
+ # The primary model below points at a server that is not there, so the request
9
+ # fails to connect and ruby_llm moves to the fallback: the model you named. The
10
+ # loop reports it as a `:fallback` event.
11
+ require "nexo"
12
+ require_relative "support/model"
13
+
14
+ abort "set NEXO_PROVIDER (this example builds its fallback from NEXO_MODEL + NEXO_PROVIDER)" unless ENV["NEXO_PROVIDER"]
15
+
16
+ # Resolve the fallback through the helper's provider settings (base URL, key).
17
+ class Probe < Nexo::Agent
18
+ Examples.model(self)
19
+ end
20
+ FALLBACK, = RubyLLM.models.resolve(ENV.fetch("NEXO_MODEL"), provider: ENV.fetch("NEXO_PROVIDER").downcase, assume_model_exists: true)
21
+
22
+ RubyLLM.configure do |config|
23
+ config.openai_api_base = "http://127.0.0.1:9/v1" # nothing listens here
24
+ config.openai_api_key = "unused"
25
+ end
26
+
27
+ class Resilient < Nexo::Agent
28
+ model "gpt-4o-mini" # the primary: unreachable in this example
29
+ provider :openai
30
+ assume_model_exists true
31
+
32
+ # Everything in this block is ruby_llm's `RubyLLM::Agent` DSL. What Nexo owns —
33
+ # model, instructions, tools, mcp, skills — is declared outside it, and refused
34
+ # inside it.
35
+ llm do
36
+ fallbacks FALLBACK
37
+ temperature 0.2
38
+ # Cut any single tool result past a quarter of the context window. A model
39
+ # outside ruby_llm's registry has no known window, so say what it is.
40
+ context_budget per_result: 0.25, window: 32_000
41
+ end
42
+
43
+ instructions "Answer in one sentence."
44
+ end
45
+
46
+ if __FILE__ == $PROGRAM_NAME
47
+ abort "set NEXO_LIVE=1 to run this live example" unless ENV["NEXO_LIVE"]
48
+
49
+ response = Resilient.new.prompt("Why would an application declare a fallback model?") do |type, payload|
50
+ puts "fallback: #{payload.from.id} -> #{payload.to.id} (#{payload.error.class})" if type == :fallback
51
+ end
52
+ puts "answer: #{response.content}"
53
+
54
+ chat = Resilient.new.chat
55
+ puts "on the chat: temperature=#{chat.temperature.inspect} budget=#{chat.context_budget.inspect}"
56
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ # A team of specialists working one brief at the same time, and an editor who
4
+ # puts their work together. (After Eve's "Marketing team" template.)
5
+ #
6
+ # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b NEXO_PROVIDER=ollama ruby -Ilib examples/marketing_team.rb
7
+ #
8
+ # Eve routes with a lead agent and subagents. Nexo has no subagents: who does what
9
+ # is plain Ruby in a workflow, which is also what makes it resumable.
10
+ # `checkpoint_all` runs the three specialists concurrently and saves each result
11
+ # as it lands, so a run that fails in the editor step does not pay for the
12
+ # specialists again on `Nexo::Workflow.retry`.
13
+ require "nexo"
14
+ require_relative "support/model"
15
+
16
+ class Specialist < Nexo::Agent
17
+ Examples.model(self)
18
+ file_tools :none # they write copy; they need no files and get no tools
19
+ end
20
+
21
+ class Positioning < Specialist
22
+ instructions "You write product positioning. Given a brief, reply with one positioning statement and three proof points. No preamble."
23
+ end
24
+
25
+ class Social < Specialist
26
+ instructions "You write social posts. Given a brief, reply with three short posts for developers, each under 240 characters. No hashtags, no preamble."
27
+ end
28
+
29
+ class Email < Specialist
30
+ instructions "You write launch emails. Given a brief, reply with a subject line and a body of at most 90 words. No preamble."
31
+ end
32
+
33
+ class Editor < Specialist
34
+ instructions "You are an editor. You receive drafts from three specialists. Make them agree with each other, " \
35
+ "remove anything the brief does not support, and return one markdown document with the sections " \
36
+ "Positioning, Social and Email."
37
+ end
38
+
39
+ class LaunchCampaign < Nexo::Workflow
40
+ TEAM = {"positioning" => Positioning, "social" => Social, "email" => Email}.freeze
41
+
42
+ def call(payload)
43
+ brief = payload[:brief]
44
+
45
+ # Three model calls in flight at once; each result is a checkpoint of its own.
46
+ drafts = checkpoint_all(TEAM.transform_values { |specialist| -> { ask(specialist, brief) } })
47
+
48
+ campaign = checkpoint(:edit) do
49
+ ask(Editor, "Brief:\n#{brief}\n\n" + drafts.map { |name, draft| "## #{name}\n#{draft}" }.join("\n\n"))
50
+ end
51
+
52
+ artifact("campaign.md", content: campaign)
53
+ {sections: drafts.keys}
54
+ end
55
+
56
+ private
57
+
58
+ def ask(agent_class, text)
59
+ agent = agent_class.new
60
+ agent.prompt(text).content
61
+ ensure
62
+ agent&.close
63
+ end
64
+ end
65
+
66
+ BRIEF = <<~TXT
67
+ Product: Nexo 0.16, an open-source Ruby gem for building AI agents on ruby_llm.
68
+ What is new: agents get file tools gated by permissions, a failed run can be
69
+ retried without repeating finished steps, and a run reports the tokens it used.
70
+ Install: gem "nexo_ai" in the Gemfile.
71
+ Audience: Ruby and Rails developers. Tone: plain, no hype.
72
+ TXT
73
+
74
+ if __FILE__ == $PROGRAM_NAME
75
+ abort "set NEXO_LIVE=1 to run this live example" unless ENV["NEXO_LIVE"]
76
+
77
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
78
+ run = LaunchCampaign.run(brief: BRIEF)
79
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
80
+
81
+ puts "status: #{run.status} in #{elapsed.round(1)}s"
82
+ puts "checkpoints: #{(run.state.keys - Nexo::Workflow::RESERVED_STATE_KEYS).inspect}"
83
+ puts
84
+ puts Nexo::Workflow.artifact_body(run.artifacts.find { |artifact| artifact["name"] == "campaign.md" })
85
+ end
@@ -5,17 +5,19 @@
5
5
  # Uses the official filesystem MCP server (npx, no credentials) so you can watch the
6
6
  # safe-by-default gate in action end to end:
7
7
  # * read tools are on the mcp_allow list -> the model can use them
8
- # * write_file is NOT on the list -> the gate returns { error: ... } (denied)
8
+ # * write_file is NOT on the list -> under :read_only it is not attached,
9
+ # so the model has no tool to write with
9
10
  #
10
11
  # Requires: `npx` on PATH, and a model. MCP ships with ruby_llm — no extra gem.
11
12
  #
12
- # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b ruby -Ilib examples/mcp_filesystem.rb /tmp
13
+ # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b NEXO_PROVIDER=ollama ruby -Ilib examples/mcp_filesystem.rb /tmp
13
14
  #
14
15
  # Nothing here is provider-specific: set NEXO_MODEL to any ruby_llm-supported model.
15
16
  require "nexo"
17
+ require_relative "support/model"
16
18
 
17
19
  class FileExplorer < Nexo::Agent
18
- model ENV.fetch("NEXO_MODEL") # provider-neutral; e.g. gemma3:12b via Ollama
20
+ Examples.model(self) # NEXO_MODEL, plus NEXO_PROVIDER=ollama for a local model
19
21
  permissions :read_only # safe default
20
22
 
21
23
  # The server names its tools like ruby_llm's file tools (read_file, search_files),
@@ -29,7 +31,8 @@ class FileExplorer < Nexo::Agent
29
31
  command: "npx",
30
32
  args: ["-y", "@modelcontextprotocol/server-filesystem", ENV.fetch("FS_ROOT", "/tmp")]
31
33
 
32
- # Opt IN to read tools only. write_file is deliberately absent -> denied by the gate.
34
+ # Opt IN to read tools only. write_file is deliberately absent, so it is never
35
+ # offered to the model.
33
36
  mcp_allow %w[read_file read_text_file list_directory search_files directory_tree]
34
37
 
35
38
  instructions "You explore a filesystem via MCP tools. Read and list only; never modify files."
@@ -44,9 +47,11 @@ if __FILE__ == $PROGRAM_NAME
44
47
  puts "== Allowed path: listing + reading under #{root} =="
45
48
  puts agent.prompt("List the files in #{root} and summarize what the first text file contains.").content
46
49
 
47
- puts "\n== Denied path: ask it to write (the gate should refuse) =="
50
+ puts "\n== Denied path: ask it to write (it has no tool to do it) =="
48
51
  puts agent.prompt("Create a file #{root}/nexo_probe.txt containing the word HELLO.").content
49
- # Expect the model to report it could not write: the write_file MCP call returns
52
+ # Expect the model to report it could not write. Under :read_only an MCP tool that
53
+ # is not in mcp_allow is not attached (since 0.14), so there is no write_file to
54
+ # call. The gate still refuses a call that reaches it another way, with
50
55
  # { error: "mcp tool write_file denied in read_only mode (not in mcp_allow)" }.
51
56
  ensure
52
57
  agent.close # tear down the stdio server subprocess
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Several calls waiting for approval at once, answered by key.
4
+ #
5
+ # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b NEXO_PROVIDER=ollama ruby -Ilib examples/multiple_approvals.rb
6
+ #
7
+ # Under `:approve` a call nobody has decided is held before the tool runs, and
8
+ # the run suspends. A model response can ask for more than one gated call:
9
+ # `run.state["__approvals_pending__"]` lists every one with the key to answer it
10
+ # under, and `resume(id, approvals: {key => true | false})` answers them together.
11
+ require "nexo"
12
+ require "tmpdir"
13
+ require_relative "support/model"
14
+
15
+ WORKSPACE = Dir.mktmpdir("nexo-approvals")
16
+
17
+ class Publisher < Nexo::Agent
18
+ Examples.model(self)
19
+ permissions :approve
20
+ instructions "You write files with the write_file tool when asked. Do not ask for confirmation."
21
+ end
22
+
23
+ class PublishNotes < Nexo::Workflow
24
+ cwd WORKSPACE
25
+ sandbox :local
26
+ agent Publisher
27
+
28
+ def call(_payload)
29
+ {reply: run_agent("Create two files: public.md containing 'release notes' and " \
30
+ "secret.md containing 'internal only'. Write both now.").content}
31
+ end
32
+ end
33
+
34
+ if __FILE__ == $PROGRAM_NAME
35
+ abort "set NEXO_LIVE=1 to run this live example" unless ENV["NEXO_LIVE"]
36
+
37
+ run = PublishNotes.run
38
+ # A host answers until the run stops asking: a model may ask for both writes in
39
+ # one response, or one at a time, or phrase the second attempt differently.
40
+ 5.times do
41
+ break unless run.status == "suspended"
42
+
43
+ pending = run.state["__approvals_pending__"]
44
+ puts "waiting for a decision on #{pending.size} call(s):"
45
+ answers = pending.to_h do |call|
46
+ approved = !call["tool"].to_s.include?("secret") # this "human" refuses the secret file
47
+ puts " #{approved ? "approve" : "decline"} #{call["capability"]} #{call["tool"]}"
48
+ [call["key"], approved]
49
+ end
50
+ run = Nexo::Workflow.resume(run.id, approvals: answers)
51
+ end
52
+
53
+ puts "status: #{run.status}"
54
+ puts "reply: #{run.result && run.result["reply"]}"
55
+ puts "on disk: #{Dir.children(WORKSPACE).sort.inspect} (secret.md was declined)"
56
+ end
@@ -8,25 +8,38 @@
8
8
  # backend; Fetch reads the allow-listed hosts. Nexo ships NO search backend — the
9
9
  # host injects one where marked below.
10
10
  #
11
- # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b ruby -Ilib examples/news_search.rb
11
+ # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b NEXO_PROVIDER=ollama ruby -Ilib examples/news_search.rb
12
12
  #
13
13
  # Nothing provider-specific: set NEXO_MODEL to any ruby_llm-supported model.
14
14
  require "nexo"
15
+ require_relative "support/model"
16
+
17
+ # A stand-in search backend: it answers every query with the same three pages.
18
+ class StaticIndex
19
+ PAGES = [
20
+ {title: "Hacker News front page", url: "https://hnrss.org/frontpage", snippet: "Today's most discussed technology stories."},
21
+ {title: "NPR text-only", url: "https://text.npr.org/", snippet: "Top US and world news, text only."},
22
+ {title: "CNN Lite", url: "https://lite.cnn.com/", snippet: "Latest headlines, text only."}
23
+ ].freeze
24
+
25
+ def search(_query) = PAGES
26
+ end
15
27
 
16
28
  class NewsSearch < Nexo::Agent
17
- model ENV.fetch("NEXO_MODEL")
29
+ Examples.model(self)
18
30
 
19
31
  # :search + :fetch are default-denied (like :shell). Grant both explicitly.
20
32
  permissions Nexo::Permissions.new(mode: :read_only, allow: %i[read glob fetch search])
21
33
 
22
- # Nexo ships NO backend. Inject your own provider adapter here — any object
23
- # responding to `search(query, **opts) -> [{title:, url:, snippet:}]`:
24
- #
25
- # search_backend YourAdapter.new(ENV.fetch("SEARCH_API_KEY"))
34
+ # Nexo ships NO backend: a search provider is yours to choose. A backend is any
35
+ # object responding to `search(query) -> [{title:, url:, snippet:}]`. This one
36
+ # is a stand-in so the example runs; replace it with an adapter for a real
37
+ # provider, e.g. `search_backend YourAdapter.new(ENV.fetch("SEARCH_API_KEY"))`.
38
+ search_backend StaticIndex.new
26
39
 
27
40
  fetch_allow %w[lite.cnn.com text.npr.org hnrss.org]
28
41
 
29
- skills :news_summary # teaches WHICH sites + HOW to summarize (examples/skills/news_summary)
42
+ skills "news-summary" # teaches WHICH sites + HOW to summarize (examples/skills/news-summary)
30
43
 
31
44
  instructions <<~TXT
32
45
  Use the search tool to discover today's top stories, then fetch the most relevant
@@ -40,10 +53,6 @@ Nexo.configure { |c| c.skills_path = File.expand_path("skills", __dir__) }
40
53
  if __FILE__ == $PROGRAM_NAME
41
54
  abort "set NEXO_LIVE=1 to run this live example" unless ENV["NEXO_LIVE"]
42
55
 
43
- unless NewsSearch.search_backend
44
- abort "inject a search_backend in examples/news_search.rb before running (Nexo ships none)"
45
- end
46
-
47
56
  summary = NewsSearch.new.prompt("Search for and summarize today's top stories.")
48
57
  puts summary.content
49
58
  end
@@ -5,19 +5,20 @@
5
5
  # The agent may fetch ONLY the allow-listed hosts (SSRF/egress guard). :fetch is a
6
6
  # default-denied capability, so the agent runs with an explicit fetch grant.
7
7
  #
8
- # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b ruby -Ilib examples/news_summary.rb
8
+ # NEXO_LIVE=1 NEXO_MODEL=gemma3:12b NEXO_PROVIDER=ollama ruby -Ilib examples/news_summary.rb
9
9
  #
10
10
  # Nothing provider-specific: set NEXO_MODEL to any ruby_llm-supported model.
11
11
  require "nexo"
12
+ require_relative "support/model"
12
13
 
13
14
  class NewsSummary < Nexo::Agent
14
- model ENV.fetch("NEXO_MODEL")
15
+ Examples.model(self)
15
16
 
16
17
  # :fetch is default-denied (like :shell). Grant it explicitly + scope hosts tightly.
17
18
  permissions Nexo::Permissions.new(mode: :read_only, allow: %i[read glob fetch])
18
19
  fetch_allow %w[hnrss.org lite.cnn.com text.npr.org]
19
20
 
20
- skills :news_summary # teaches WHICH sites + HOW to summarize (examples/skills/news_summary)
21
+ skills "news-summary" # teaches WHICH sites + HOW to summarize (examples/skills/news-summary)
21
22
 
22
23
  instructions <<~TXT
23
24
  You summarize current news from the allow-listed sites using the fetch tool, following