rubik 0.12.0 → 0.13.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f668c26bd4967d506b511a23d21f1a9afe91cc0c94b6d007b39e4dd1d4102e7e
4
- data.tar.gz: b4d12df2cc31b33e86a97c5a1a2f050f42bbc612169eb54d36a96d238f9b5445
3
+ metadata.gz: c6a9e85889683534d644e9f88c1f076dce8e91e0503a2e40a823149d6d1ca359
4
+ data.tar.gz: 925f5cfb990e06c0f7d1b9ac4911db249853bfde78e9902c20b104b114541f5e
5
5
  SHA512:
6
- metadata.gz: 4072b8c92a9f9990227c1b72996a48942fd1008a849bf9e6d6ff74c80f1448dbd10d5409158e85e1c7c5ae54463f69b0b9a68b07a542a87cb51a837e8bee4751
7
- data.tar.gz: 5a9679b4f592d999e9602af4758327347f7bf5a84eee8e0b70bb5591830eab73a65dfcc1cf7bb78ae171b2e4b32bea9ef52c8ce6f704d9806db9d440e5cef9fc
6
+ metadata.gz: 2b8c173c30baa1c4b9ad7b9cfdc9baabd98d8c8191569693a7baba5299d03448d0ed1f6f163e7b9d4ea77c9732fdb4f2ad47a8959304758f9f9cc0f4d6548df5
7
+ data.tar.gz: 409d010dc7e497735871c2e0f84690675f10c0e00750137dea7c1cd6ee93a44c94c861b2d1345f8ac4a005e3801bf76506c2c7f0858681eb0e8f807d2a414292
data/ATTRIBUTION.md CHANGED
@@ -121,7 +121,7 @@ SOFTWARE.
121
121
  | **`strings-ansi`** | Piotr Murach | MIT | ANSI-aware string truncation and alignment for REPL formatters. |
122
122
  | **`reline`** | Hiroshi SHIBATA & Ruby Team | Ruby License / BSD-2-Clause | Line-editing, history navigation, autocompletion hooks, and headless terminal adaptation. |
123
123
  | **`prism`** | Kevin Newton & Ruby Core Team | MIT | High-performance Ruby parsing and AST extraction ([`Rubik::AST::RubyExtractor`](lib/rubik/ast/ruby_extractor.rb)). |
124
- | **`minitest`** | Ryan Davis & seattlerb | MIT | Fast, modular test suite powering Rubik's 4,600+ unit, integration, and contract tests. |
124
+ | **`minitest`** | Ryan Davis & seattlerb | MIT | Fast, modular test suite powering Rubik's 4,700+ unit, integration, and contract tests. |
125
125
  | **`rubocop`** | Bozhidar Batsov & contributors | MIT | Static code analysis, style enforcement, and architectural hygiene gates. |
126
126
  | **`benchmark`, `logger`, `pstore`, `reline`, `fiddle`** | Ruby core / rubygems teams | Ruby License / BSD-2-Clause | Ruby stdlib gems pinned explicitly in `rubik.gemspec` as they are unbundled from the default set in Ruby 3.4/3.5. |
127
127
 
data/CHANGELOG.md CHANGED
@@ -6,6 +6,42 @@ commits, 2026-08-23 → 2026-10-09, see `git log`).
6
6
 
7
7
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
8
8
 
9
+ ## [Unreleased]
10
+
11
+ ## [0.13.0] - 2026-11-17
12
+
13
+ The connect-wizard minor: provider binding collapses into an interactive
14
+ `!connect` / `rubik connect` flow that selects the provider from the
15
+ models.dev catalog, validates the key live, and routes the secret through
16
+ the existing SecretPolicy — while a review-and-CodeQL round keeps the
17
+ wizard's URL and key-normalization parsing linear-time and enriches its
18
+ model menus from catalog metadata.
19
+
20
+ ### Added
21
+
22
+ - **Connect wizard (`!connect` / `rubik connect`):** an interactive provider
23
+ setup wizard that collapses provider binding into a few answers — provider
24
+ selection (pinned favorites plus the full models.dev catalog behind a
25
+ type-to-filter submenu), a catalog-prefilled endpoint, a masked API key
26
+ with live validation (auth failures re-ask; unreachable endpoints offer
27
+ save-anyway), model selection from the provider's live list or the catalog
28
+ (context limits written from catalog metadata), and role binding
29
+ (default/fast/advanced). Nothing is written before the confirm step; the
30
+ commit goes through the existing Config verbs so the key lands in the OS
31
+ secret store and global scope is the default. The wizard is offered once on
32
+ first run when boot resolves no LLM client (`connect.first_run_offer`
33
+ knob), and the catalog cache (24h TTL, stale-while-error) lives under
34
+ `~/.rubik/cache/`.
35
+
36
+ ### Fixed
37
+
38
+ - **Wizard review hardening:** the provider-key trimming is linear-time
39
+ (`delete_prefix`/`delete_suffix`, no anchored-alternation regex) to keep
40
+ CodeQL's polynomial-ReDoS check clean; hostless http/https URLs are
41
+ rejected; live model listings are enriched with models.dev catalog
42
+ metadata (context limit, tool-call support); and success notes print even
43
+ when the flow stores no secret (Ollama / env-var / skipped-key).
44
+
9
45
  ## [0.12.0] - 2026-11-17
10
46
 
11
47
  The retry-and-resume minor: the LLM transport's hardcoded rate-limit and 5xx
@@ -1784,7 +1820,8 @@ installation section.
1784
1820
  - Context: serialized index mutations, snapshot-outside-lock reconcile,
1785
1821
  streaming-first truncation.
1786
1822
 
1787
- [Unreleased]: https://github.com/ozgurulukir/rubik/compare/v0.12.0...HEAD
1823
+ [Unreleased]: https://github.com/ozgurulukir/rubik/compare/v0.13.0...HEAD
1824
+ [0.13.0]: https://github.com/ozgurulukir/rubik/compare/v0.12.0...v0.13.0
1788
1825
  [0.12.0]: https://github.com/ozgurulukir/rubik/compare/v0.11.0...v0.12.0
1789
1826
  [0.11.0]: https://github.com/ozgurulukir/rubik/compare/v0.10.0...v0.11.0
1790
1827
  [0.10.0]: https://github.com/ozgurulukir/rubik/compare/v0.9.1...v0.10.0
data/bin/rubik CHANGED
@@ -18,8 +18,18 @@ trap("INT") do
18
18
  end
19
19
 
20
20
  options = {}
21
+
22
+ # `rubik connect`: standalone provider setup wizard — runs and exits before
23
+ # the trust gate and Shell boot (same run-and-exit shape as --list-sessions);
24
+ # the wizard writes global-scope config only, --project stays an explicit flag.
25
+ if ARGV.first == "connect"
26
+ ARGV.shift
27
+ require "rubik/cli/connect"
28
+ exit(Rubik::CLI::Connect.run(argv: ARGV))
29
+ end
30
+
21
31
  OptionParser.new do |opts|
22
- opts.banner = "Usage: rubik [options]"
32
+ opts.banner = "Usage: rubik [options] | rubik connect"
23
33
 
24
34
  opts.on("-v", "--version", "Show version") do
25
35
  puts "rubik version #{Rubik::VERSION}"
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../connect"
4
+
5
+ module Rubik
6
+ module CLI
7
+ # `rubik connect` — the standalone connect-wizard runner. Boots no
8
+ # Shell and no workspace trust gate (same run-and-exit shape as
9
+ # --list-sessions): the wizard writes global-scope config only, and a
10
+ # project-scope choice stays an explicit --project flag (plaintext
11
+ # project secrets are still refused by SecretPolicy).
12
+ module Connect
13
+ module_function
14
+
15
+ USAGE = "Usage: rubik connect [--project|--global]"
16
+
17
+ # -> exit code: 0 connected, 1 cancelled/failed, 2 non-interactive.
18
+ # prompt:/probe: are test seams (scripted prompt, stubbed probes).
19
+ def run(argv:, input: $stdin, output: $stdout, root_dir: Dir.pwd, home_dir: nil, prompt: nil, probe: nil)
20
+ if argv.intersect?(["--help", "-h"])
21
+ output.puts USAGE
22
+ return 0
23
+ end
24
+ if argv.intersect?(["--session", "-s"])
25
+ output.puts USAGE
26
+ output.puts " rubik connect yalnızca kalıcı kapsamlara yazar; oturum-kapsamı için REPL içinde !provider add kullanın."
27
+ output.puts " rubik connect writes persistent scopes only; use !provider add in the REPL for a session-scoped provider."
28
+ return 1
29
+ end
30
+
31
+ scope = argv.include?("--project") || argv.include?("-p") ? :project : :global
32
+ config = Rubik::Config.new(root_dir: root_dir, home_dir: home_dir)
33
+ ui = Rubik::Connect::PromptUI.new(input: input, output: output,
34
+ theme: Rubik::UI::Theme.for(output, config), prompt: prompt)
35
+ wizard = Rubik::Connect::Wizard.new(config: config, ui: ui, io: output, scope: scope,
36
+ probe: probe,
37
+ catalog_loader: -> { Rubik::Connect::ModelsDev.load(home_dir: config.home_dir) })
38
+ result = wizard.run
39
+
40
+ if result[:reason] == :non_interactive
41
+ output.puts "Etkileşimsiz oturum — sihirbaz çalışamaz. 'rubik' ile REPL başlatıp !connect kullanın " \
42
+ "veya !provider add <name> [type] <url> [--key=...] sözdizimini uygulayın."
43
+ output.puts "Non-interactive session — start the REPL and run !connect, or use !provider add flags."
44
+ return 2
45
+ end
46
+ output.puts "Çıkmak için 'rubik' ile REPL'i başlatın / Start the REPL with 'rubik'." if result[:ok]
47
+ result[:ok] ? 0 : 1
48
+ end
49
+ end
50
+ end
51
+ end
@@ -57,6 +57,7 @@ module Rubik
57
57
  "native" => "auto"
58
58
  },
59
59
  "router" => { "mode" => "auto", "sticky" => true },
60
+ "connect" => { "first_run_offer" => true }, # connect wizard first-run offer (repl/lifecycle.rb)
60
61
  "repair" => { "max_attempts" => 3 },
61
62
  "sandbox" => {
62
63
  "enabled" => false,
@@ -41,6 +41,7 @@ module Rubik
41
41
  "tools.native" => { type: :enum, allowed: ["auto", "on", "off"] },
42
42
  "router.mode" => { type: :enum, allowed: ["auto", "manual", "fast", "advanced"] },
43
43
  "router.sticky" => { type: :boolean },
44
+ "connect.first_run_offer" => { type: :boolean },
44
45
  "repair.max_attempts" => { type: :integer, min: 0 },
45
46
  "sandbox.enabled" => { type: :boolean },
46
47
  # Free-form: the driver registry is dynamically extensible (plugins
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "uri"
6
+
7
+ module Rubik
8
+ module Connect
9
+ # Minimal GET-only JSON transport for the connect wizard: catalog fetch
10
+ # and live endpoint probes. Deliberately probe-grade — short fixed
11
+ # timeouts, no retry budgets, no pooling; the retry-hardened POST path
12
+ # stays in LLM::HTTPClient. Never raises: outcome hashes only, so the
13
+ # wizard can degrade honestly (retry / save-anyway / cancel) instead of
14
+ # unwinding mid-question.
15
+ module Http
16
+ DEFAULT_TIMEOUT = 10
17
+ DEFAULT_OPEN_TIMEOUT = 5
18
+
19
+ module_function
20
+
21
+ # GET `url` and parse the body as JSON.
22
+ # -> {ok: true, status:, json:}
23
+ # | {ok: false, error:, status:, reason:, body:}
24
+ # reason: :invalid_url (non-http(s) scheme), :unreachable (transport),
25
+ # :http_error (non-2xx), :bad_response (2xx non-JSON).
26
+ def get_json(url, headers: {}, timeout: DEFAULT_TIMEOUT, open_timeout: DEFAULT_OPEN_TIMEOUT, fetcher: nil)
27
+ uri = parse_url(url)
28
+ return uri unless uri.is_a?(URI::Generic) # parse failure outcome
29
+
30
+ response = perform(uri, headers: headers, timeout: timeout, open_timeout: open_timeout, fetcher: fetcher)
31
+ # Duck-typed: real responses and test doubles alike expose code/body;
32
+ # a Hash means the transport itself already failed (outcome hash).
33
+ return response unless response.respond_to?(:code) && response.respond_to?(:body)
34
+
35
+ status = response.code.to_i
36
+ body = response.body.to_s
37
+ return { ok: false, error: "HTTP #{status}", status: status, reason: :http_error, body: body } unless status.between?(200, 299)
38
+
39
+ json = parse_json(body)
40
+ return { ok: false, error: "invalid JSON response", status: status, reason: :bad_response } if json.nil?
41
+
42
+ { ok: true, status: status, json: json }
43
+ end
44
+
45
+ def parse_json(body)
46
+ JSON.parse(body)
47
+ rescue JSON::ParserError
48
+ nil
49
+ end
50
+
51
+ def parse_url(url)
52
+ parsed = begin
53
+ URI.parse(url.to_s)
54
+ rescue URI::Error
55
+ nil
56
+ end
57
+ return invalid_url_outcome if parsed.nil?
58
+ return invalid_url_outcome unless parsed.is_a?(URI::HTTP) || parsed.is_a?(URI::HTTPS)
59
+ return invalid_url_outcome if parsed.host.nil? || parsed.host.empty?
60
+
61
+ parsed
62
+ end
63
+
64
+ def invalid_url_outcome
65
+ { ok: false, error: "only http/https URLs are supported", status: nil, reason: :invalid_url }
66
+ end
67
+
68
+ def perform(uri, headers:, timeout:, open_timeout:, fetcher:)
69
+ if fetcher
70
+ fetcher.call(uri)
71
+ else
72
+ http = Net::HTTP.new(uri.host, uri.port)
73
+ http.use_ssl = uri.is_a?(URI::HTTPS)
74
+ http.open_timeout = open_timeout
75
+ http.read_timeout = timeout
76
+ request = Net::HTTP::Get.new(uri)
77
+ headers.each { |key, value| request[key] = value }
78
+ http.request(request)
79
+ end
80
+ rescue StandardError => e
81
+ { ok: false, error: "#{e.class}: #{e.message}", status: nil, reason: :unreachable }
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require_relative "http"
5
+
6
+ module Rubik
7
+ module Connect
8
+ # models.dev catalog integration: fetch the provider/model directory
9
+ # (a single literal URL — no user input reaches the request, so the
10
+ # fetch carries no SSRF surface), cache it under ~/.rubik/cache with a
11
+ # 24h TTL, degrade to the stale cache when the network fails, and
12
+ # classify providers into the shapes rubik's registry can speak
13
+ # (openai_compatible | anthropic | ollama-local).
14
+ module ModelsDev
15
+ CATALOG_URL = "https://models.dev/catalog.json"
16
+ CACHE_FILE = "models_dev_catalog.json"
17
+ TTL_SECONDS = 24 * 60 * 60
18
+ FETCH_TIMEOUT = 30 # the document is multi-MB JSON
19
+ # Mirrors LLM::Registry's per-model fallback so manual entries behave
20
+ # exactly like !provider add defaults.
21
+ DEFAULT_CONTEXT_LIMIT = 32_768
22
+
23
+ # Everyday providers first; the 300+ catalog tail stays behind the
24
+ # wizard's filter submenu. api is the offline fallback when the
25
+ # catalog is unreachable — online runs prefer the catalog's own api
26
+ # field (so catalog updates win over hardcoded bases).
27
+ PINNED = [
28
+ { id: "openai", label: "OpenAI", type: "openai_compatible", api: "https://api.openai.com/v1", catalog_id: "openai" },
29
+ { id: "anthropic", label: "Anthropic", type: "anthropic", api: "https://api.anthropic.com", catalog_id: "anthropic" },
30
+ { id: "openrouter", label: "OpenRouter", type: "openai_compatible", api: "https://openrouter.ai/api/v1", catalog_id: "openrouter" },
31
+ { id: "deepseek", label: "DeepSeek", type: "openai_compatible", api: "https://api.deepseek.com", catalog_id: "deepseek" },
32
+ { id: "groq", label: "Groq", type: "openai_compatible", api: "https://api.groq.com/openai/v1", catalog_id: "groq" },
33
+ { id: "mistral", label: "Mistral", type: "openai_compatible", api: "https://api.mistral.ai/v1", catalog_id: "mistral" },
34
+ { id: "xai", label: "xAI (Grok)", type: "openai_compatible", api: "https://api.x.ai/v1", catalog_id: "xai" },
35
+ # rubik has no native Gemini client; the documented OpenAI-compatible
36
+ # base speaks Bearer auth and /models — the catalog's native api
37
+ # field for "google" must NOT be used here.
38
+ { id: "gemini", label: "Google (Gemini)", type: "openai_compatible", api: "https://generativelanguage.googleapis.com/v1beta/openai", catalog_id: "google",
39
+ use_catalog_api: false },
40
+ { id: "ollama", label: "Ollama (yerel / local)", type: "ollama", api: "http://localhost:11434", catalog_id: nil }
41
+ ].freeze
42
+
43
+ module_function
44
+
45
+ # -> {catalog: Hash(provider_id => entry), source: :fresh|:cache|:stale|:none}
46
+ # Resolution order: valid cache -> stale-accepted cache (network
47
+ # failed) -> empty (:none). The cache envelope is
48
+ # {"fetched_at" => epoch, "providers" => {...}}; a corrupt file is a
49
+ # miss, never a raise.
50
+ def load(home_dir:, now: -> { Time.now.to_i }, fetcher: nil, ttl: TTL_SECONDS)
51
+ path = cache_path(home_dir)
52
+ cached = read_cache(path)
53
+
54
+ return { catalog: cached[:providers], source: :cache } if cached && (now.call.to_i - cached[:fetched_at]) < ttl
55
+
56
+ fetched = Http.get_json(CATALOG_URL, timeout: FETCH_TIMEOUT, fetcher: fetcher)
57
+ if fetched[:ok] && fetched[:json].is_a?(Hash) && fetched[:json]["providers"].is_a?(Hash)
58
+ write_cache(path, fetched[:json]["providers"], now.call.to_i)
59
+ { catalog: fetched[:json]["providers"], source: :fresh }
60
+ elsif cached
61
+ { catalog: cached[:providers], source: :stale }
62
+ else
63
+ { catalog: {}, source: :none }
64
+ end
65
+ end
66
+
67
+ def cache_path(home_dir)
68
+ File.join(home_dir.to_s, ".rubik", "cache", CACHE_FILE)
69
+ end
70
+
71
+ def read_cache(path)
72
+ parsed = JSON.parse(File.read(path))
73
+ providers = parsed["providers"]
74
+ fetched_at = parsed["fetched_at"]
75
+ return nil unless providers.is_a?(Hash) && fetched_at.is_a?(Numeric)
76
+
77
+ { providers: providers, fetched_at: fetched_at.to_i }
78
+ rescue StandardError
79
+ nil
80
+ end
81
+
82
+ # Atomic replace (tmp + rename) so a crash mid-write can never leave a
83
+ # half-JSON cache behind for the stale path to trip on. The pid
84
+ # suffix keeps two concurrent rubik processes from interleaving one
85
+ # fixed tmp file.
86
+ def write_cache(path, providers, fetched_at)
87
+ dir = File.dirname(path)
88
+ FileUtils.mkdir_p(dir)
89
+ tmp = "#{path}.#{Process.pid}.tmp"
90
+ File.write(tmp, JSON.generate({ "fetched_at" => fetched_at, "providers" => providers }))
91
+ File.rename(tmp, path)
92
+ rescue StandardError
93
+ nil
94
+ end
95
+
96
+ # True when the catalog entry speaks an OpenAI-compatible API rubik
97
+ # can drive: explicit npm package, or an api URL with a compatible
98
+ # path shape (versioned / OpenAI / compatible / PaaS) and not an
99
+ # /anthropic/ path. Entries without any api URL are dropped — the
100
+ # submenu can't prefill a base URL for them (they remain reachable
101
+ # via the custom-endpoint branch).
102
+ def openai_compatible?(entry)
103
+ return false unless entry.is_a?(Hash)
104
+
105
+ npm = entry["npm"].to_s
106
+ return true if ["@ai-sdk/openai-compatible", "@ai-sdk/openai"].include?(npm)
107
+
108
+ api = entry["api"].to_s
109
+ return false if api.empty? || api.include?("/anthropic")
110
+
111
+ api.match?(%r{/v\d+|/openai|/compatible|/paas/})
112
+ end
113
+
114
+ # Catalog entries the submenu offers, sorted by display name.
115
+ # -> [{id:, name:, api:, entry:}]
116
+ def compatible_providers(catalog)
117
+ return [] unless catalog.is_a?(Hash)
118
+
119
+ compatible = catalog.filter_map do |id, entry|
120
+ next unless openai_compatible?(entry)
121
+
122
+ { id: id.to_s, name: entry["name"].to_s.empty? ? id.to_s : entry["name"].to_s,
123
+ api: entry["api"], entry: entry }
124
+ end
125
+ compatible.sort_by { |p| p[:name].downcase }
126
+ end
127
+
128
+ # Models of one catalog provider, best first: widest context on top,
129
+ # tool-capable models ahead of plain ones at equal width.
130
+ # -> [{id:, name:, context_limit:, output_limit:, tool_call:}]
131
+ def models_for(catalog, provider_id)
132
+ entry = catalog.is_a?(Hash) ? catalog[provider_id] : nil
133
+ return [] unless entry.is_a?(Hash) && entry["models"].is_a?(Hash)
134
+
135
+ entries = entry["models"].filter_map do |id, m|
136
+ next unless m.is_a?(Hash)
137
+
138
+ limit = m["limit"].is_a?(Hash) ? m["limit"] : {}
139
+ { id: id.to_s, name: m["name"].to_s.empty? ? id.to_s : m["name"].to_s,
140
+ context_limit: limit["context"].is_a?(Numeric) ? limit["context"].to_i : nil,
141
+ output_limit: limit["output"].is_a?(Numeric) ? limit["output"].to_i : nil,
142
+ tool_call: m["tool_call"] == true }
143
+ end
144
+ entries.sort_by { |m| [m[:context_limit].to_i * -1, m[:name].downcase] }
145
+ end
146
+
147
+ # The pre-highlighted model choice: widest tool-capable context wins;
148
+ # falls back to the first entry. Models are already context-sorted.
149
+ def default_model(models)
150
+ models.find { |m| m[:tool_call] } || models.first
151
+ end
152
+
153
+ # Sanitizes a catalog/display name into a providers.<id> storage key
154
+ # (downcase, alnum/dash/underscore only). Mirrors the downcasing the
155
+ # registry applies when registering provider specs. The trim stays
156
+ # linear (delete_prefix/suffix) — regex-based end-trimming on
157
+ # uncontrolled catalog names triggers CodeQL's polynomial-ReDoS check.
158
+ def provider_key(name)
159
+ key = name.to_s.downcase.gsub(/[^a-z0-9_]+/, "-")
160
+ key.delete_prefix("-").delete_suffix("-")
161
+ end
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "http"
4
+
5
+ module Rubik
6
+ module Connect
7
+ # Live endpoint validation for the connect wizard: one cheap GET per
8
+ # provider family, with the API key supplied — so a typo'd credential
9
+ # fails here (with a re-ask loop) instead of on the first real turn.
10
+ # No retries: the wizard owns the retry/save-anyway/cancel menu.
11
+ module Probes
12
+ TIMEOUT = 8
13
+ OLLAMA_TIMEOUT = 4
14
+ AUTH_STATUSES = [401, 403].freeze
15
+ NO_LISTING_STATUSES = [404, 405].freeze
16
+
17
+ module_function
18
+
19
+ # Outcome shape shared by all probes:
20
+ # ok: true -> endpoint answered and (when possible) listed models
21
+ # auth_failed: key was explicitly rejected (401/403)
22
+ # reachable: the host answered at all (network + TLS succeeded)
23
+ # models: live model ids when the endpoint lists them
24
+ # note: honest detail for the wizard's report
25
+ # The api_key never appears in `note`.
26
+
27
+ def openai_compatible(base_url, api_key: nil, timeout: TIMEOUT, fetcher: nil)
28
+ res = Http.get_json(models_url(base_url), headers: bearer_headers(api_key), timeout: timeout, fetcher: fetcher)
29
+ classify(res) { |json| model_ids(json) }
30
+ end
31
+
32
+ # Anthropic exposes a free GET /v1/models on the fixed API base (the
33
+ # provider class has no endpoint parameter, so a custom gateway base
34
+ # cannot be probed here — custom gateways belong to the
35
+ # openai_compatible branch anyway).
36
+ def anthropic(api_key:, timeout: TIMEOUT, fetcher: nil)
37
+ res = Http.get_json("https://api.anthropic.com/v1/models",
38
+ headers: { "x-api-key" => api_key.to_s, "anthropic-version" => "2023-06-01" },
39
+ timeout: timeout, fetcher: fetcher)
40
+ classify(res) { |json| model_ids(json) }
41
+ end
42
+
43
+ # Ollama's /api/tags doubles as the liveness check AND the installed
44
+ # model list — the wizard's model menu is built from it.
45
+ def ollama(host, timeout: OLLAMA_TIMEOUT, fetcher: nil)
46
+ res = Http.get_json("#{host.to_s.delete_suffix('/')}/api/tags", timeout: timeout, fetcher: fetcher)
47
+ classify(res) do |json|
48
+ json["models"].filter_map { |m| m["name"] if m.is_a?(Hash) }
49
+ end
50
+ end
51
+
52
+ # REST root for the model listing: OpenAI-compatible bases end in a
53
+ # version segment or the Gemini-compat "/openai" tail; those take
54
+ # /models directly, bare hosts get the conventional /v1/models.
55
+ def models_url(base_url)
56
+ base = base_url.to_s.delete_suffix("/")
57
+ if base.match?(%r{/v\d+\z}) || base.end_with?("/openai")
58
+ "#{base}/models"
59
+ else
60
+ "#{base}/v1/models"
61
+ end
62
+ end
63
+
64
+ def bearer_headers(api_key)
65
+ api_key.to_s.empty? ? {} : { "Authorization" => "Bearer #{api_key}" }
66
+ end
67
+
68
+ def model_ids(json)
69
+ Array(json["data"]).filter_map { |m| m["id"] if m.is_a?(Hash) }
70
+ end
71
+
72
+ def classify(res)
73
+ case res[:reason]
74
+ when :invalid_url, :unreachable
75
+ { ok: false, auth_failed: false, reachable: false, models: [], note: res[:error].to_s }
76
+ when :http_error
77
+ if AUTH_STATUSES.include?(res[:status])
78
+ { ok: false, auth_failed: true, reachable: true, models: [], note: "HTTP #{res[:status]} — anahtar reddedildi / key rejected" }
79
+ elsif NO_LISTING_STATUSES.include?(res[:status])
80
+ { ok: true, auth_failed: false, reachable: true, models: [],
81
+ note: "model listesi yayınlanmıyor (HTTP #{res[:status]}) — model adını elle girin / no model listing; enter the name manually" }
82
+ else
83
+ { ok: false, auth_failed: false, reachable: true, models: [], note: "HTTP #{res[:status]}" }
84
+ end
85
+ when :bad_response
86
+ { ok: false, auth_failed: false, reachable: true, models: [], note: res[:error].to_s }
87
+ else # 2xx JSON
88
+ models = yield(res[:json])
89
+ { ok: true, auth_failed: false, reachable: true, models: models.is_a?(Array) ? models : [] }
90
+ end
91
+ rescue StandardError => e
92
+ { ok: false, auth_failed: false, reachable: true, models: [], note: "#{e.class}: #{e.message}" }
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "tty-prompt"
4
+ require_relative "../ui/capability"
5
+ require_relative "../ui/theme"
6
+ require_relative "../repl/interrupt_handler"
7
+
8
+ module Rubik
9
+ module Connect
10
+ # Prompt port for the connect wizard: the exact TTY::Prompt operations
11
+ # the flow needs (select / ask / secret / yes?), with UI::Dialog's
12
+ # sentinel contract (:cancelled / :non_interactive) and the same
13
+ # injectable-prompt test seam. Lives outside UI::Dialog because the
14
+ # wizard runs shell-less (rubik connect boots no Shell) and needs
15
+ # typed prompts (masked key entry, yes/no) Dialog does not offer.
16
+ class PromptUI
17
+ CANCELLED = :cancelled
18
+ NON_INTERACTIVE = :non_interactive
19
+
20
+ attr_reader :theme
21
+
22
+ def initialize(input:, output:, theme: nil, prompt: nil)
23
+ @input = input
24
+ @output = output
25
+ @theme = theme || Rubik::UI::Theme.for(output, nil)
26
+ # Injected prompt => forced-interactive (tests); same seam as Dialog.
27
+ @prompt = prompt
28
+ end
29
+
30
+ def interactive?
31
+ return true if @prompt
32
+
33
+ Rubik::UI::Capability.interactive?(input: @input, output: @output)
34
+ end
35
+
36
+ # Single-choice menu; `filter: true` lets users type to narrow long
37
+ # lists (the 300+ catalog tail depends on it). Returns the chosen
38
+ # String or a sentinel.
39
+ def select(question, choices, default: nil)
40
+ raw do |p|
41
+ # tty-prompt select defaults are 1-based; 0 raises out of range.
42
+ default_index = choices.index(default).to_i + 1
43
+ p.select(question, choices, filter: true, per_page: 10, cycle: true,
44
+ default: default_index)
45
+ end
46
+ end
47
+
48
+ # Free-text question; empty input accepts `default` when given.
49
+ def ask(question, default: nil)
50
+ raw do |p|
51
+ if default.nil?
52
+ p.ask(question)
53
+ else
54
+ # default rides both channels: the option (consumed by injected
55
+ # test doubles) and the TTY modifier block (real prompts) —
56
+ # TTY treats them as equivalent settings, idempotent to double-apply.
57
+ p.ask(question, default: default.to_s) { |q| q.default(default.to_s) }
58
+ end
59
+ end
60
+ end
61
+
62
+ # Masked credential entry (no echo). Real TTY::Prompt exposes #mask;
63
+ # injected test doubles implement the wizard-level #secret.
64
+ def secret(question)
65
+ raw do |p|
66
+ if p.respond_to?(:mask)
67
+ p.mask(question)
68
+ else
69
+ p.secret(question)
70
+ end
71
+ end
72
+ end
73
+
74
+ def yes?(question, default: true)
75
+ raw { |p| p.yes?(question, default: default) { |q| q.default(default) } }
76
+ end
77
+
78
+ # Plain line output for notices/reports; never a sentinel source.
79
+ def puts(line)
80
+ @output.puts line
81
+ end
82
+
83
+ # Theme-aware text styling for wizard output (frames, success/error
84
+ # lines); degrades to the raw text off color-capable terminals.
85
+ def paint(text, style)
86
+ @theme.paint(text, style)
87
+ end
88
+
89
+ # Wraps a blocking fetch in a live spinner on capable terminals and
90
+ # stays silent elsewhere; always yields.
91
+ def spinner(message)
92
+ if Rubik::UI::Capability.spinner?(@output)
93
+ spin_out = Rubik::UI::Capability.unwrap_tee(@output) || $stdout
94
+ spin = TTY::Spinner.new("[:spinner] #{message}", format: :spin, hide_cursor: true, clear: true,
95
+ output: spin_out)
96
+ spin.auto_spin
97
+ begin
98
+ yield
99
+ ensure
100
+ spin.stop
101
+ end
102
+ else
103
+ yield
104
+ end
105
+ end
106
+
107
+ private
108
+
109
+ # The one sentinel funnel: every prompt operation degrades to
110
+ # :non_interactive off a live TTY and to :cancelled on interrupt or
111
+ # prompt failure, restoring the console either way (Dialog
112
+ # discipline). A swallowed non-interrupt error is never silent —
113
+ # debug_warn names it so a prompt-layer bug cannot pose as a user
114
+ # cancellation.
115
+ def raw
116
+ return NON_INTERACTIVE unless interactive?
117
+
118
+ yield(@prompt || build_prompt)
119
+ rescue Interrupt
120
+ CANCELLED
121
+ rescue StandardError => e
122
+ Rubik::Platform.debug_warn("connect prompt failed (#{e.class}: #{e.message}) — treated as cancel")
123
+ CANCELLED
124
+ ensure
125
+ restore_console
126
+ end
127
+
128
+ def build_prompt
129
+ TTY::Prompt.new(input: @input, output: Rubik::UI::Capability.unwrap_tee(@output) || $stdout)
130
+ end
131
+
132
+ def restore_console
133
+ Rubik::REPL::InterruptHandler.restore_console_after_interrupt
134
+ rescue StandardError
135
+ nil
136
+ end
137
+ end
138
+ end
139
+ end