Class: Rubino::CLI::Commands
- Inherits:
-
Thor
- Object
- Thor
- Rubino::CLI::Commands
- Defined in:
- lib/rubino/cli/commands.rb
Overview
Main Thor command class. All subcommands are registered here.
Constant Summary collapse
- TAGLINE =
One-line description of what rubino IS, surfaced as a top-line tagline in ‘rubino –help` / `rubino help` — Thor’s stock command list opens cold with “Commands:” and never says what the tool does or where to start (F-help). Wrap Thor’s #help to print a tagline above the listing and a “Getting started: run ‘rubino setup`” hint below it, so a brand-new user lands on the first action instead of a bare verb table.
"rubino — an AI coding agent that reads, edits, and runs code."- GETTING_STARTED =
"Getting started: run `rubino setup` to configure a model, " \ "then `rubino chat` (or `rubino \"your prompt\"`)."
- HELP_FLAGS =
Help flags recognized on any top-level command (#134).
["--help", "-h"].freeze
- HELP_WRAP_COLUMNS =
Wrap subcommand help so ‘chat –help` / `prompt –help` stay within 80 columns (#217). Thor’s stock #print_options lays the flags and their descriptions out in a 2-column table padded to the WIDEST flag — and the boolean variants (‘[–no-x], [–skip-x]`) push that column past 60, so every description row overflowed 80 (the longest hit 137) with no wrapping. Render each option as its flag line followed by the description wrapped + indented on its own line(s) instead: bounded by construction, and it reads cleaner than the ragged padded table.
80- HELP_DESC_INDENT =
6
Class Method Summary collapse
-
.chat_like_command(given_args) ⇒ Object
The chat-like command an arg list dispatches to (‘chat` or `prompt`), or nil when it isn’t one.
-
.clean_thor_message(error, given_args) ⇒ Object
Normalizes a Thor dispatch/argument error message into rubino’s own voice, so every pre-run failure reads as one clean ‘rubino: <msg>` line instead of mixing Thor’s raw ‘ERROR: …`/`Usage: …` text with our hand-crafted unknown-command/unknown-flag voice (copy-consistency).
-
.closest_command(name) ⇒ Object
The closest known top-level command/subcommand to a mistyped
name, for the unknown-command did-you-mean (F2). -
.default_command ⇒ Object
Allow passing prompt directly as default task: rubino “my prompt”.
- .exit_on_failure? ⇒ Boolean
-
.help(shell, subcommand = false) ⇒ Object
rubocop:disable Style/OptionalBooleanParameter – overrides Thor’s own ‘def help(shell, subcommand = false)`; the positional boolean is Thor’s public signature (instance #help calls it positionally), not ours to change.
-
.json_output_requested?(given_args) ⇒ Boolean
True when the raw CLI args ask for a machine-readable one-shot mode — ‘–json`, or `–output-format json|stream-json` (hyphen or underscore, `=`-joined or space-separated).
-
.known_flag_tokens(command) ⇒ Object
The set of accepted flag spellings for a command — every declared ‘–long`, `–no-long` (booleans), and short `-x` alias — so a typo is caught but a real flag in any spelling is accepted.
- .print_options(shell, options, group_name = nil) ⇒ Object
-
.report_early_error(given_args, message, exit_code: 1) ⇒ Object
Surfaces a pre-run error (a Thor dispatch/argument error caught in #start, or any other boot-time failure that escapes a command body) in the invocation’s chosen output format, then exits non-zero (#327).
-
.start(given_args = ARGV, config = {}) ⇒ Object
Intercept ‘–version`/`-v` at dispatch (#32).
-
.unknown_leading_flag(given_args) ⇒ Object
The first LEADING ‘–flag` of a chat/prompt invocation that isn’t a declared option, or nil (F7).
-
.value_flag?(command, flag) ⇒ Boolean
True when a flag carries a value (so its next token is the value, not a positional).
-
.wrap_help_description(description) ⇒ Object
Greedy word-wrap of a flag description to HELP_WRAP_COLUMNS, each line indented HELP_DESC_INDENT.
Instance Method Summary collapse
- #chat(prompt = nil) ⇒ Object
- #doctor ⇒ Object
- #prompt(*args) ⇒ Object
- #server ⇒ Object
- #setup ⇒ Object
- #tls_cert ⇒ Object
- #tools ⇒ Object
- #update ⇒ Object
- #version ⇒ Object
Class Method Details
.chat_like_command(given_args) ⇒ Object
The chat-like command an arg list dispatches to (‘chat` or `prompt`), or nil when it isn’t one. A bare invocation (‘rubino “hi”`, `rubino –frobnicate`) falls to the default command (chat); an explicit `rubino prompt …` / `rubino chat …` is named outright. Subcommands and other top-level commands return nil — Thor already rejects unknown flags for those, and only chat/prompt have a positional that swallows a typo.
192 193 194 195 196 197 198 199 |
# File 'lib/rubino/cli/commands.rb', line 192 def self.chat_like_command(given_args) first = Array(given_args).first.to_s return first if %w[chat prompt].include?(first) # A leading flag / quoted prompt (not a known command) → default command. return "chat" if first.start_with?("-") || !commands.key?(first.tr("-", "_")) nil end |
.clean_thor_message(error, given_args) ⇒ Object
Normalizes a Thor dispatch/argument error message into rubino’s own voice, so every pre-run failure reads as one clean ‘rubino: <msg>` line instead of mixing Thor’s raw ‘ERROR: …`/`Usage: …` text with our hand-crafted unknown-command/unknown-flag voice (copy-consistency).
* An unknown command (Thor::UndefinedCommandError) becomes
"unknown command 'X'. Did you mean `setup`? Run `rubino --help`."
— the closest-match did-you-mean mirrors the in-REPL slash hint (F2),
replacing Thor's terser "Could not find command … Did you mean? …".
* An argument/usage error (Thor::InvocationError, e.g. a command called
with stray args/flags) has its internal `ERROR: ` prefix and trailing
`Usage: …` line stripped, leaving just the plain sentence.
Any other Thor/Configuration error passes through unchanged.
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
# File 'lib/rubino/cli/commands.rb', line 154 def self.(error, given_args) name = Array(given_args).first.to_s # Only the TOP-LEVEL unknown command gets rubino's did-you-mean voice. A # nested miss (`rubino sessions frobnicate`) also surfaces as an # UndefinedCommandError, but `given_args.first` there is the VALID parent # ("sessions") — suggesting against the top-level roster would be wrong, so # those fall through to Thor's own (cleaned) "Could not find command …". if error.is_a?(Thor::UndefinedCommandError) && !commands.key?(name.tr("-", "_")) msg = "unknown command '#{name}'." if (suggestion = closest_command(name)) msg += " Did you mean `#{suggestion}`?" end return "#{msg} Run `rubino --help`." end # Drop Thor's `ERROR: ` lead and its `Usage: "…"` continuation line(s), # keeping the first clean sentence (e.g. the "was called with arguments" # line) — never the raw two-line `ERROR:/Usage:` block. error..to_s.sub(/\AERROR: /, "").split("\nUsage:", 2).first.strip end |
.closest_command(name) ⇒ Object
The closest known top-level command/subcommand to a mistyped name, for the unknown-command did-you-mean (F2). Uses the same stdlib DidYouMean SpellChecker the in-REPL slash hint uses; best-effort (nil on any hiccup).
178 179 180 181 182 183 184 |
# File 'lib/rubino/cli/commands.rb', line 178 def self.closest_command(name) require "did_you_mean" dict = commands.keys.map(&:to_s) DidYouMean::SpellChecker.new(dictionary: dict).correct(name.to_s).first rescue StandardError nil end |
.default_command ⇒ Object
Allow passing prompt directly as default task: rubino “my prompt”
52 53 54 |
# File 'lib/rubino/cli/commands.rb', line 52 def self.default_command :chat end |
.exit_on_failure? ⇒ Boolean
16 17 18 |
# File 'lib/rubino/cli/commands.rb', line 16 def self.exit_on_failure? true end |
.help(shell, subcommand = false) ⇒ Object
rubocop:disable Style/OptionalBooleanParameter – overrides Thor’s own ‘def help(shell, subcommand = false)`; the positional boolean is Thor’s public signature (instance #help calls it positionally), not ours to change.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/rubino/cli/commands.rb', line 33 def self.help(shell, subcommand = false) # Only decorate the TOP-LEVEL command listing (`rubino --help`), not a # per-command help page (`rubino help chat`) — those are dispatched with # the command name and handled by super unchanged. if subcommand super return end shell.say(TAGLINE) shell.say super shell.say(GETTING_STARTED) shell.say end |
.json_output_requested?(given_args) ⇒ Boolean
True when the raw CLI args ask for a machine-readable one-shot mode —‘–json`, or `–output-format json|stream-json` (hyphen or underscore, `=`-joined or space-separated). Decided from the raw argv (NOT Thor’s parsed options) because the error we’re reporting can be the very failure that aborted option parsing, so parsed options may be unavailable. Mirrors ChatCommand#json_requested? so the early-error envelope matches the in-command one.
292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
# File 'lib/rubino/cli/commands.rb', line 292 def self.json_output_requested?(given_args) args = Array(given_args).map(&:to_s) return true if args.include?("--json") args.each_with_index do |a, i| if ["--output-format", "--output_format"].include?(a) val = args[i + 1].to_s.tr("-", "_") return true if %w[json stream_json].include?(val) elsif (m = a.match(/\A--output[-_]format=(.+)\z/)) return true if %w[json stream_json].include?(m[1].tr("-", "_")) end end false end |
.known_flag_tokens(command) ⇒ Object
The set of accepted flag spellings for a command — every declared ‘–long`, `–no-long` (booleans), and short `-x` alias — so a typo is caught but a real flag in any spelling is accepted.
236 237 238 239 240 241 242 243 244 245 246 247 248 249 |
# File 'lib/rubino/cli/commands.rb', line 236 def self.known_flag_tokens(command) opts = commands[command]&. || {} # --help/-h and the global --version/-v are always valid spellings; the # latter is handled at the top of #start when LEADING, but a non-leading # `chat --version` must still fall through to Thor (not be rejected as # "unknown"), preserving the pre-F7 dispatch behaviour. tokens = HELP_FLAGS + %w[--version -v] opts.each_value do |o| tokens << "--#{o.name.tr("_", "-")}" tokens << "--no-#{o.name.tr("_", "-")}" if o.type == :boolean Array(o.aliases).each { |a| tokens << a } end tokens.uniq end |
.print_options(shell, options, group_name = nil) ⇒ Object
318 319 320 321 322 323 324 325 326 327 328 329 |
# File 'lib/rubino/cli/commands.rb', line 318 def self.(shell, , group_name = nil) return if .empty? shell.say(group_name ? "#{group_name} options:" : "Options:") .reject(&:hide).each do |option| shell.say(" #{option.usage(0)}") next unless option.description wrap_help_description(option.description).each { |line| shell.say(line) } end shell.say "" end |
.report_early_error(given_args, message, exit_code: 1) ⇒ Object
Surfaces a pre-run error (a Thor dispatch/argument error caught in #start, or any other boot-time failure that escapes a command body) in the invocation’s chosen output format, then exits non-zero (#327). Under –output-format json|stream-json the message becomes the same is_error:true, … envelope ChatCommand#fail_arg! emits for an empty prompt / invalid –output-format, so a json consumer ALWAYS gets a parseable object on stdout; under text it is the clean ‘rubino: <msg>` stderr line. The JSON path is wholly best-effort: an envelope hiccup must never mask the underlying failure, so it falls back to the stderr line.
271 272 273 274 275 276 277 278 279 280 281 282 283 |
# File 'lib/rubino/cli/commands.rb', line 271 def self.report_early_error(given_args, , exit_code: 1) if json_output_requested?(given_args) begin $stdout.puts JSON.generate(Output::ResultSerializer.arg_error(message: )) $stdout.flush rescue StandardError warn "rubino: #{}" end else warn "rubino: #{}" end exit(exit_code) end |
.start(given_args = ARGV, config = {}) ⇒ Object
Intercept ‘–version`/`-v` at dispatch (#32). Thor otherwise routes a bare `rubino –version` to the default `chat` task, which treats the flag as a prompt and fails with an API-key error. Handle it here —print the version and exit — before any chat/credential handling.
Likewise intercept ‘rubino <command> –help` (#134): Thor 1.x only maps a LEADING help flag to the help task, so `chat –help`/`prompt –help` used to fall through as an unknown option, become the positional prompt, and start a REAL agent run (provider call + memory writes). Reroute to Thor’s own ‘help <command>` before option parsing. Thor subcommands (config/memory/sessions/jobs) already handle their own `–help` and keep their richer subcommand listing.
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 |
# File 'lib/rubino/cli/commands.rb', line 71 def self.start(given_args = ARGV, config = {}) if ["--version", "-v"].include?(given_args.first) puts "rubino v#{Rubino::VERSION}" return end cmd = given_args.first.to_s.tr("-", "_") if given_args.drop(1).intersect?(HELP_FLAGS) && commands.key?(cmd) && !subcommands.include?(cmd) return super(["help", cmd], config) end # Reject an unknown LEADING flag before it is swallowed into the prompt # (F7). `chat` is the default command, so `rubino --frobnicate …` (or # `rubino prompt --frobnicate`) routes to chat/prompt and a TYPO'D flag # silently became part of the message text (or an empty-prompt run) # instead of erroring. Validate the leading `--flags` of a chat/prompt # invocation against that command's declared options here and surface a # clean "unknown flag" instead. A legitimate prompt that merely CONTAINS # `--` text (`rubino "run git log --oneline"`) is untouched: only a flag # in the LEADING run (before the first positional word) is checked. if (bad = unknown_leading_flag(given_args)) report_early_error(given_args, "unknown flag '#{bad}'. Run `rubino #{chat_like_command(given_args)} --help` for valid flags") end # Force Thor's own `start` to RE-RAISE a Thor::Error (unknown command, # bad/malformed flag, ambiguous command, a subcommand's `raise # Thor::Error`) instead of swallowing it into a bare stderr line + exit # (its default). We catch it below so EVERY dispatch/argument error is # surfaced format-aware (#327): a clean stderr line under text, a # well-formed JSON error envelope on STDOUT under --output-format # json|stream-json — never an empty stdout, and never a raw backtrace. super(given_args, config.merge(debug: true)) rescue Rubino::Database::BusyError => e # Final backstop (#333/#359): a SUSTAINED concurrent-migration lock that # outlived the connection retry budget must surface as a clean single # line + non-zero exit at this one chokepoint — never a raw Sequel/ # SQLite backtrace from whichever command happened to touch the DB. # (Rubino::Database::BusyError is DEFINED in the always-loaded errors.rb # so naming it here can never NameError before the DB is autoloaded — # #445-regression fix.) warn "rubino: #{e.}" exit(1) rescue Thor::Error, Rubino::ConfigurationError => e # A pre-run error that reached the boot chokepoint: # * Thor::Error — a dispatch/argument failure (Thor::UndefinedCommandError # carrying its own "Did you mean?" suggestion, MalformattedArgumentError # for a bad `--max-turns abc`, a subcommand's `raise Thor::Error`). # * Rubino::ConfigurationError — a source-raised config error, today a # careless RUBINO_HOME pointing at a file / read-only parent (F13, # raised by Rubino.ensure_directories!). # Surface it in the format the invocation asked for: under json/stream-json # emit the #327 envelope on stdout so automation can parse the failure (the # prior behaviour left stdout EMPTY for Thor errors, or leaked a raw Errno # backtrace for the home error); otherwise the clean one-line stderr Thor # itself would have printed. Never a raw backtrace; exit non-zero. report_early_error(given_args, (e, given_args)) rescue SystemCallError => e # A filesystem/OS syscall (Errno::*) that reached the boot chokepoint # WITHOUT going through Rubino.ensure_directories!'s file-vs-directory # guard — today a `config set`/`config unset` write whose RUBINO_HOME # points at an existing file, so Util::AtomicFile.mkdir_p raised a raw # ~25-frame fileutils Errno::EEXIST backtrace (MED). Normalize EVERY such # Errno here, the same single chokepoint, into the SAME clean one-liner # chat/setup already emit (clean_errno_message strips Ruby's internal # ` @ <syscall> - <path>` tail): a `rubino: <reason>` stderr line under # text, the #327 envelope on stdout under json/stream-json. Never a raw # backtrace; exit non-zero. Deliberately NOT broadened to StandardError — # only OS-level Errno failures are normalized; a real bug still surfaces. report_early_error(given_args, Rubino.(e.)) end |
.unknown_leading_flag(given_args) ⇒ Object
The first LEADING ‘–flag` of a chat/prompt invocation that isn’t a declared option, or nil (F7). “Leading” = appears before the first POSITIONAL word, so a ‘–`-containing prompt is never misread: once a non-flag token is seen, the rest is the prompt and is not inspected. Value-taking flags consume their following token so `–model foo` doesn’t treat ‘foo` as a positional. Only inspects chat/prompt; other commands return nil (Thor handles their flags).
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
# File 'lib/rubino/cli/commands.rb', line 208 def self.unknown_leading_flag(given_args) command = chat_like_command(given_args) return nil unless command args = Array(given_args).map(&:to_s) # Drop the explicit command word when present; for the default-command # path the whole list is the chat args. args = args.drop(1) if %w[chat prompt].include?(args.first) known = known_flag_tokens(command) i = 0 while i < args.size tok = args[i] break unless tok.start_with?("-") && tok != "-" # first positional ⇒ stop flag = tok.split("=", 2).first return flag unless known.include?(flag) # A known value-flag with a space-separated value consumes the next # token so it isn't mistaken for the first positional. i += value_flag?(command, flag) && !tok.include?("=") ? 2 : 1 end nil end |
.value_flag?(command, flag) ⇒ Boolean
True when a flag carries a value (so its next token is the value, not a positional). Booleans don’t; everything else does.
253 254 255 256 257 258 259 260 |
# File 'lib/rubino/cli/commands.rb', line 253 def self.value_flag?(command, flag) opts = commands[command]&. || {} opt = opts.values.find do |o| long = "--#{o.name.tr("_", "-")}" long == flag || Array(o.aliases).include?(flag) end opt && opt.type != :boolean end |
.wrap_help_description(description) ⇒ Object
Greedy word-wrap of a flag description to HELP_WRAP_COLUMNS, each line indented HELP_DESC_INDENT. Wrapped here (not via Thor’s print_wrapped) so the bound is the fixed 80 the spec checks, not the live terminal width. A single word longer than the budget is emitted on its own line rather than dropped.
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 |
# File 'lib/rubino/cli/commands.rb', line 336 def self.wrap_help_description(description) indent = " " * HELP_DESC_INDENT budget = HELP_WRAP_COLUMNS - HELP_DESC_INDENT lines = [] line = +"" description.to_s.split(/\s+/).each do |word| if line.empty? line << word elsif line.length + 1 + word.length <= budget line << " " << word else lines << (indent + line) line = +word end end lines << (indent + line) unless line.empty? lines end |
Instance Method Details
#chat(prompt = nil) ⇒ Object
420 421 422 423 424 |
# File 'lib/rubino/cli/commands.rb', line 420 def chat(prompt = nil) # Support: rubino chat "prompt" as shorthand for -q opts = .to_h.merge(prompt ? { query: prompt } : {}) ChatCommand.new(opts).execute end |
#doctor ⇒ Object
491 492 493 |
# File 'lib/rubino/cli/commands.rb', line 491 def doctor DoctorCommand.new.execute end |
#prompt(*args) ⇒ Object
448 449 450 451 452 |
# File 'lib/rubino/cli/commands.rb', line 448 def prompt(*args) query = args.join(" ") opts = .to_h.merge(query: query) ChatCommand.new(opts).execute end |
#server ⇒ Object
478 479 480 |
# File 'lib/rubino/cli/commands.rb', line 478 def server ServerCommand.new().execute end |
#setup ⇒ Object
356 357 358 |
# File 'lib/rubino/cli/commands.rb', line 356 def setup SetupCommand.new.execute end |
#tls_cert ⇒ Object
486 487 488 |
# File 'lib/rubino/cli/commands.rb', line 486 def tls_cert $stdout.write(API::TLS.ensure_cert!) end |
#tools ⇒ Object
470 471 472 |
# File 'lib/rubino/cli/commands.rb', line 470 def tools ToolsCommand.new.execute end |
#update ⇒ Object
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 |
# File 'lib/rubino/cli/commands.rb', line 501 def update ui = Rubino.ui current = Rubino::VERSION case Rubino::UpdateCheck.install_method when :gem ok = system(*Rubino::UpdateCheck.gem_update_command) unless ok ui.warning("gem update failed. If this is a permission error, re-run the installer or try `gem update --user-install #{Rubino::UpdateCheck::GEM_NAME}`.") return end new_v = Rubino::UpdateCheck.installed_gem_version(Rubino::UpdateCheck::GEM_NAME) if new_v && Gem::Version.new(new_v) > Gem::Version.new(current) ui.info("rubino is now on v#{new_v} (was v#{current}).") ui.status("Restart any running rubino sessions to pick up the new version.") else ui.info("rubino is already up to date (v#{current}).") end else ui.warning("rubino wasn't installed from RubyGems (built from source / dev checkout).") ui.status("Re-run the installer to update:") ui.status(" curl -fsSL https://raw.githubusercontent.com/Jhonnyr97/rubino-agent/main/install.sh | bash") end ensure # Drop the cached notice so the boot footer doesn't linger after update. Rubino::UpdateCheck.clear_cache! end |