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.
@@ -0,0 +1,488 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "models_dev"
4
+ require_relative "probes"
5
+ require_relative "../llm/openai_compatible"
6
+ require_relative "../ui/frame"
7
+
8
+ module Rubik
9
+ module Connect
10
+ # The provider connect wizard: one flow shared by `!connect` (REPL),
11
+ # `rubik connect` (CLI) and the boot offer. Gathers a provider binding
12
+ # as an in-memory plan, live-validates it, and only then commits —
13
+ # through the existing Config verbs, so SecretPolicy routes the
14
+ # credential into the OS keyring and cancellation before the confirm
15
+ # step is a zero-write event.
16
+ #
17
+ # Commit ordering: provider spec first (one atomic Hash write carrying
18
+ # the full models array), then role specs. An interrupt mid-commit
19
+ # leaves an inert-but-valid provider; roles re-attach with `!model set`.
20
+ class Wizard
21
+ CUSTOM_LABEL = "Özel uç nokta / Custom endpoint"
22
+ MANUAL_MODEL_LABEL = "✎ Elle gir / Enter manually"
23
+ S_PROVIDER = "Sağlayıcı seçin / Choose a provider:"
24
+ S_ALL_CATALOG = "Tüm katalog / All catalog providers:"
25
+ S_ENDPOINT = "Uç nokta / Endpoint:"
26
+ S_AUTH = "Kimlik doğrulama / Authentication:"
27
+ S_MODEL = "Model seçin (önerilen üstte) / Pick a model (recommended first):"
28
+ S_ROLES = "Roller / Roles:"
29
+ MAX_PROBE_ATTEMPTS = 5
30
+
31
+ ROLE_DEFAULT = "Sadece default / default only"
32
+ ROLE_DEFAULT_FAST = "default + fast"
33
+ ROLE_ALL = "default + fast + advanced"
34
+ ROLE_NONE = "Rol atama yok / no role binding"
35
+ ROLE_MENU = [ROLE_DEFAULT, ROLE_DEFAULT_FAST, ROLE_ALL, ROLE_NONE].freeze
36
+
37
+ AUTH_KEY = "API anahtarı gireceğim / I'll enter an API key"
38
+ AUTH_ENV = "Ortam değişkeni kullanacağım / I'll use an environment variable"
39
+ AUTH_SKIP = "Şimdilik atla / Skip for now"
40
+
41
+ def initialize(config:, ui:, io:, scope: :global, refresh: nil, catalog_loader: nil, probe: nil)
42
+ @config = config
43
+ @ui = ui # prompt port: questions + live-terminal notices
44
+ # @io is the transcript sink (REPL TeeIO capture / CLI stdout):
45
+ # header, summary and result lines land in the session record too.
46
+ @io = io
47
+ @scope = scope
48
+ @refresh = refresh
49
+ @catalog_loader = catalog_loader || -> { ModelsDev.load(home_dir: @config.home_dir) }
50
+ @probe = probe || Probes
51
+ @catalog = {}
52
+ @notes = []
53
+ end
54
+
55
+ # -> {ok: true, provider:, model:, roles:, scope:, notes: []}
56
+ # | {ok: false, reason: :cancelled|:non_interactive|:write_failed,
57
+ # error:, provider:, notes: []}
58
+ def run
59
+ return { ok: false, reason: :non_interactive, error: nil, provider: nil, notes: [] } unless @ui.interactive?
60
+
61
+ render_header
62
+ load_catalog
63
+ plan = select_provider
64
+ plan = ask_endpoint(plan) if plan.is_a?(Hash)
65
+ plan = ask_credential(plan) if plan.is_a?(Hash)
66
+ plan = ask_model(plan) if plan.is_a?(Hash)
67
+ roles = ask_roles if plan.is_a?(Hash)
68
+ return finish_abort(:cancelled) unless plan.is_a?(Hash) && roles.is_a?(Array)
69
+
70
+ plan[:roles] = roles
71
+ return finish_abort(:cancelled) unless confirm(plan)
72
+
73
+ commit(plan)
74
+ end
75
+
76
+ private
77
+
78
+ def finish_abort(reason)
79
+ @ui.puts @ui.paint("Sihirbaz iptal edildi — hiçbir şey yazılmadı / Wizard cancelled — nothing was written.", :dim)
80
+ { ok: false, reason: reason, error: nil, provider: nil, notes: @notes }
81
+ end
82
+
83
+ def render_header
84
+ @io.puts Rubik::UI::Frame.draw(
85
+ [@ui.paint("Sağlayıcı ekle, anahtarı doğrula, modeli bağla", :bold),
86
+ @ui.paint("Add a provider, validate its key, bind a model", :dim)],
87
+ theme: @ui.theme, width: 78,
88
+ title: @ui.paint("⚙ BAĞLANTI SİHİRBAZI / CONNECT WIZARD", :accent)
89
+ )
90
+ end
91
+
92
+ def load_catalog
93
+ result = @ui.spinner("Katalog indiriliyor / Fetching model catalog…") { @catalog_loader.call }
94
+ @catalog = result[:catalog].is_a?(Hash) ? result[:catalog] : {}
95
+ case result[:source]
96
+ when :stale
97
+ note("katalog önbelleği bayat — eski katalog gösteriliyor / showing a stale cached catalog")
98
+ when :none
99
+ note("katalog alınamadı — manuel mod / catalog unavailable — manual mode")
100
+ end
101
+ end
102
+
103
+ def note(text)
104
+ @notes << text
105
+ end
106
+
107
+ # ── Step 1: provider ──────────────────────────────────────────────
108
+ def select_provider
109
+ choices = []
110
+ lookup = {}
111
+ ModelsDev::PINNED.each do |pin|
112
+ entry = @catalog[pin[:catalog_id]].is_a?(Hash) ? @catalog[pin[:catalog_id]] : nil
113
+ api = catalog_api_for(pin, entry)
114
+ label = "#{pin[:label]} · #{host_of(api)}"
115
+ choices << label
116
+ lookup[label] = { id: pin[:id], label: pin[:label], type: pin[:type], base_url: api,
117
+ catalog_id: pin[:catalog_id], catalog_entry: entry }
118
+ end
119
+ choices << CUSTOM_LABEL
120
+ lookup[CUSTOM_LABEL] = :custom
121
+
122
+ compatible = ModelsDev.compatible_providers(@catalog)
123
+ all_label = "Tüm katalog / All catalog (#{compatible.size})"
124
+ if compatible.any?
125
+ choices << all_label
126
+ lookup[all_label] = :all
127
+ end
128
+
129
+ chosen = @ui.select(S_PROVIDER, choices, default: choices.first)
130
+ return :cancelled unless chosen.is_a?(String)
131
+
132
+ case lookup[chosen]
133
+ when :custom then ask_custom_provider
134
+ when :all then pick_from_catalog(compatible)
135
+ else lookup[chosen]
136
+ end
137
+ end
138
+
139
+ # Online runs prefer the catalog's own api field (catalog updates win
140
+ # over hardcoded bases); PINNED carries the offline fallback. Google's
141
+ # catalog api is the native Gemini API rubik cannot speak, so that
142
+ # pinned row opts out via use_catalog_api: false.
143
+ def catalog_api_for(pin, entry)
144
+ return pin[:api] if pin[:use_catalog_api] == false
145
+
146
+ api = entry.is_a?(Hash) ? entry["api"] : nil
147
+ api.is_a?(String) && !api.empty? ? api : pin[:api]
148
+ end
149
+
150
+ def ask_custom_provider
151
+ name = @ui.ask("Sağlayıcı adı / Provider name:")
152
+ return :cancelled unless name.is_a?(String) && !ModelsDev.provider_key(name).empty?
153
+
154
+ type = @ui.select("Tür / Type:", ["openai_compatible", "anthropic", "ollama"], default: "openai_compatible")
155
+ return :cancelled unless type.is_a?(String)
156
+
157
+ { id: ModelsDev.provider_key(name), label: name.strip, type: type,
158
+ base_url: nil, catalog_id: nil, catalog_entry: nil }
159
+ end
160
+
161
+ def pick_from_catalog(compatible)
162
+ choices = compatible.map { |p| "#{p[:name]} (#{p[:id]})" }
163
+ lookup = compatible.zip(choices).to_h { |p, label| [label, p] }
164
+ chosen = @ui.select(S_ALL_CATALOG, choices)
165
+ return :cancelled unless chosen.is_a?(String)
166
+
167
+ picked = lookup[chosen]
168
+ { id: ModelsDev.provider_key(picked[:id]), label: picked[:name], type: "openai_compatible",
169
+ base_url: picked[:api], catalog_id: picked[:id], catalog_entry: picked[:entry] }
170
+ end
171
+
172
+ # ── Step 2: endpoint ─────────────────────────────────────────────
173
+ def ask_endpoint(plan)
174
+ # AnthropicProvider honors no endpoint parameter — asking would
175
+ # invite a gateway URL the registry silently ignores; custom
176
+ # gateways belong to the custom/openai_compatible branch.
177
+ return plan if plan[:type] == "anthropic"
178
+
179
+ default = plan[:base_url] || (plan[:type] == "ollama" ? "http://localhost:11434" : "")
180
+ until (answer = request_endpoint(default)).is_a?(String) && valid_endpoint?(answer)
181
+ return :cancelled unless answer.is_a?(String)
182
+
183
+ @ui.puts @ui.paint("⚠ Geçersiz uç nokta / Endpoint must start with http:// or https://", :error)
184
+ end
185
+
186
+ plan[:base_url] = answer.strip
187
+ plan
188
+ end
189
+
190
+ def request_endpoint(default)
191
+ answer = @ui.ask(S_ENDPOINT, default: default)
192
+ answer.is_a?(String) ? answer.strip : answer
193
+ end
194
+
195
+ def valid_endpoint?(answer)
196
+ answer.to_s.start_with?("http://", "https://")
197
+ end
198
+
199
+ # ── Step 3: credential + live validation ─────────────────────────
200
+ def ask_credential(plan)
201
+ return plan if plan[:type] == "ollama"
202
+
203
+ choice = @ui.select(S_AUTH, [AUTH_KEY, AUTH_ENV, AUTH_SKIP], default: AUTH_KEY)
204
+ return :cancelled unless choice.is_a?(String)
205
+
206
+ if choice == AUTH_ENV
207
+ env = @ui.ask("Ortam değişkeni / Environment variable name:")
208
+ return :cancelled unless env.is_a?(String) && !env.strip.empty?
209
+
210
+ plan[:api_key_env] = env.strip
211
+ elsif choice == AUTH_SKIP
212
+ note("anahtar sonra ayarlanacak — doğrulama atlandı / key deferred — validation skipped")
213
+ else
214
+ key = key_with_validation(plan)
215
+ return :cancelled if key == :cancelled
216
+ return plan if key.nil? # deferred — the note is already recorded
217
+
218
+ plan[:api_key] = key
219
+ end
220
+ plan
221
+ end
222
+
223
+ # Probe → menu loop for auth failures / unreachable endpoints.
224
+ # Terminates by: storing a validated key, storing unvalidated (user
225
+ # chose save-anyway), deferring (empty entry), cancelling, or burning
226
+ # MAX_PROBE_ATTEMPTS (save last key with a note).
227
+ def key_with_validation(plan)
228
+ last_key = nil
229
+ attempts = 0
230
+ while attempts < MAX_PROBE_ATTEMPTS
231
+ key = @ui.secret("#{plan[:label]} API anahtarı / API key:")
232
+ return :cancelled unless key.is_a?(String) # interrupt / prompt failure
233
+
234
+ if key.strip.empty? # empty entry = defer, same as AUTH_SKIP
235
+ note("anahtar sonra ayarlanacak — doğrulama atlandı / key deferred — validation skipped")
236
+ return nil
237
+ end
238
+
239
+ last_key = key
240
+ attempts += 1
241
+ result = @ui.spinner("Doğrulanıyor / Validating…") { probe_plan(plan, key) }
242
+ if result[:ok]
243
+ plan[:live_models] = result[:models] if result[:models].any?
244
+ return key
245
+ end
246
+
247
+ note(result[:note]) if result[:note]
248
+
249
+ action = @ui.select(failure_question(result), failure_menu(result))
250
+ return :cancelled unless action.is_a?(String)
251
+
252
+ return last_key if action.start_with?("Doğrulamadan", "Yine de")
253
+ return :cancelled if action.start_with?("İptal")
254
+ end
255
+ note("doğrulama denemeleri tükendi — kaydediliyor / validation attempts exhausted — saving unvalidated")
256
+ last_key
257
+ end
258
+
259
+ def probe_plan(plan, key)
260
+ if plan[:type] == "anthropic"
261
+ @probe.anthropic(api_key: key)
262
+ else
263
+ @probe.openai_compatible(plan[:base_url], api_key: key)
264
+ end
265
+ end
266
+
267
+ def failure_question(result)
268
+ if result[:auth_failed]
269
+ "Anahtar reddedildi (#{result[:note]}). Ne yapalım? / Key rejected. What now?"
270
+ else
271
+ "Uç nokta doğrulanamadı (#{result[:note]}). Ne yapalım? / Could not validate the endpoint. What now?"
272
+ end
273
+ end
274
+
275
+ def failure_menu(result)
276
+ if result[:auth_failed]
277
+ ["Anahtarı yeniden gir / Re-enter key", "Doğrulamadan kaydet / Save without validation", "İptal / Cancel"]
278
+ else
279
+ ["Anahtarı yeniden gir / Re-enter key", "Yine de kaydet / Save anyway", "İptal / Cancel"]
280
+ end
281
+ end
282
+
283
+ # ── Step 4: model ────────────────────────────────────────────────
284
+ def ask_model(plan)
285
+ menu = build_model_menu(plan)
286
+ chosen = @ui.select(S_MODEL, menu[:choices], default: menu[:default])
287
+ return :cancelled unless chosen.is_a?(String)
288
+
289
+ if chosen == MANUAL_MODEL_LABEL
290
+ name = @ui.ask("Model adı / Model name:")
291
+ return :cancelled unless name.is_a?(String) && !name.strip.empty?
292
+
293
+ limit = @ui.ask("Bağlam sınırı (token) / Context limit (tokens):", default: ModelsDev::DEFAULT_CONTEXT_LIMIT.to_s)
294
+ return :cancelled unless limit.is_a?(String)
295
+
296
+ plan[:model] = { name: name.strip, context_limit: parse_limit(limit) || ModelsDev::DEFAULT_CONTEXT_LIMIT }
297
+ else
298
+ picked = menu[:lookup][chosen]
299
+ plan[:model] = { name: picked[:id], context_limit: picked[:context_limit] || ModelsDev::DEFAULT_CONTEXT_LIMIT }
300
+ end
301
+ plan
302
+ end
303
+
304
+ # "200k" / "1M" suffixes are how users type context windows; bare
305
+ # integers pass through, junk returns nil (caller falls back to the
306
+ # default limit).
307
+ def parse_limit(raw)
308
+ match = raw.to_s.strip.downcase.match(/\A(\d+(?:\.\d+)?)\s*(k|m)?\z/)
309
+ return nil unless match
310
+
311
+ value = match[1].to_f
312
+ value *= 1000 if match[2] == "k"
313
+ value *= 1_000_000 if match[2] == "m"
314
+ value.to_i.positive? ? value.to_i : nil
315
+ end
316
+
317
+ # Live model ids from the probes win (they are what the endpoint
318
+ # actually serves); the catalog list is the fallback, annotated with
319
+ # context limits and tool support. Manual entry is always available —
320
+ # it is the whole flow when catalog AND live listing are absent. For
321
+ # ollama the /api/tags listing doubles as the liveness probe and is
322
+ # fetched here (there is no credential step to hang it on).
323
+ def build_model_menu(plan)
324
+ lookup = {}
325
+ fetch_live_models(plan)
326
+ live = plan[:live_models].is_a?(Array) && plan[:live_models].any?
327
+ catalog_models = ModelsDev.models_for(@catalog, plan[:catalog_id])
328
+ if live
329
+ by_id = catalog_models.to_h { |m| [m[:id], m] }
330
+ live_entries = plan[:live_models].map { |id| by_id[id.to_s] || { id: id.to_s, context_limit: nil, tool_call: false } }
331
+ live_entries.each do |m|
332
+ label = m[:context_limit] ? "#{m[:id]} · #{compact_ctx(m[:context_limit])}#{' · tools' if m[:tool_call]}" : m[:id]
333
+ lookup[label] = m
334
+ end
335
+ recommended = ModelsDev.default_model(live_entries.select { |m| m[:context_limit] }) || live_entries.first
336
+ else
337
+ catalog_models.each do |m|
338
+ label = "#{m[:id]} · #{compact_ctx(m[:context_limit])}#{' · tools' if m[:tool_call]}"
339
+ lookup[label] = m
340
+ end
341
+ recommended = ModelsDev.default_model(catalog_models)
342
+ end
343
+ lookup[MANUAL_MODEL_LABEL] = nil
344
+ # The pre-highlighted choice: best catalog-matched live model (or
345
+ # first live id), or the catalog's recommended model mapped back to
346
+ # its label.
347
+ default_label = recommended && lookup.key(recommended) ? lookup.key(recommended).to_s : MANUAL_MODEL_LABEL
348
+ { choices: lookup.keys, lookup: lookup, default: default_label }
349
+ end
350
+
351
+ def fetch_live_models(plan)
352
+ return unless plan[:type] == "ollama"
353
+
354
+ result = @ui.spinner("Ollama modelleri alınıyor / Fetching Ollama models…") { @probe.ollama(plan[:base_url]) }
355
+ if result[:ok]
356
+ plan[:live_models] = result[:models]
357
+ else
358
+ note(result[:note].to_s)
359
+ end
360
+ end
361
+
362
+ def compact_ctx(limit)
363
+ return "?" if limit.nil?
364
+
365
+ "#{(limit.to_f / 1000).round}k"
366
+ end
367
+
368
+ # ── Step 5: roles ────────────────────────────────────────────────
369
+ def ask_roles
370
+ chosen = @ui.select(S_ROLES, ROLE_MENU, default: ROLE_DEFAULT)
371
+ return :cancelled unless chosen.is_a?(String)
372
+
373
+ case chosen
374
+ when ROLE_DEFAULT then ["default"]
375
+ when ROLE_DEFAULT_FAST then ["default", "fast"]
376
+ when ROLE_ALL then ["default", "fast", "advanced"]
377
+ else []
378
+ end
379
+ end
380
+
381
+ # ── Step 6: confirm + commit ─────────────────────────────────────
382
+ def confirm(plan)
383
+ roles_desc = plan[:roles].empty? ? "—" : plan[:roles].join(", ")
384
+ key_desc = if plan[:api_key_env]
385
+ "env: #{plan[:api_key_env]}"
386
+ elsif plan[:api_key].to_s.empty?
387
+ "yok / none"
388
+ else
389
+ "secret store'a yazılacak / stored via secret store"
390
+ end
391
+ summary = [
392
+ "#{@ui.paint('Sağlayıcı / Provider', :bold)} : #{plan[:id]} (#{plan[:type]})",
393
+ "#{@ui.paint('Uç nokta / Endpoint', :bold)} : #{plan[:base_url]}",
394
+ "#{@ui.paint('Model', :bold)} : #{plan[:model][:name]} (#{compact_ctx(plan[:model][:context_limit])} ctx)",
395
+ "#{@ui.paint('Roller / Roles', :bold)} : #{roles_desc}",
396
+ "#{@ui.paint('Anahtar / Key', :bold)} : #{key_desc}",
397
+ "#{@ui.paint('Kapsam / Scope', :bold)} : #{scope_persist_label}"
398
+ ]
399
+ @io.puts Rubik::UI::Frame.draw(summary, theme: @ui.theme, width: 78,
400
+ title: @ui.paint("⚙ BAĞLANTI ÖZETİ / CONNECTION SUMMARY", :accent))
401
+ @ui.yes?("Kaydet / Save?", default: true) == true
402
+ end
403
+
404
+ def commit(plan)
405
+ res = @config.set("providers.#{plan[:id]}", build_spec(plan), persist: @scope)
406
+ unless res[:ok]
407
+ @ui.puts @ui.paint("Yazma başarısız / Could not save: #{res[:error]}", :error)
408
+ return { ok: false, reason: :write_failed, error: res[:error], provider: plan[:id], notes: @notes }
409
+ end
410
+
411
+ role_failures = bind_roles(plan)
412
+ @refresh&.call
413
+ render_success(plan, res, role_failures)
414
+
415
+ { ok: true, provider: plan[:id], model: plan[:model][:name], roles: plan[:roles],
416
+ scope: @scope, notes: @notes }
417
+ end
418
+
419
+ # Same storage shape !provider add writes; openai_compatible endpoints
420
+ # get the same normalization (the registry re-normalizes on build, the
421
+ # probe stays on the raw base). Compacted: ollama carries no api_key.
422
+ def build_spec(plan)
423
+ {
424
+ "type" => plan[:type],
425
+ "endpoint" => spec_endpoint(plan),
426
+ "api_key" => plan[:api_key].to_s.empty? ? nil : plan[:api_key],
427
+ "api_key_env" => plan[:api_key_env],
428
+ "default_model" => plan[:model][:name],
429
+ "models" => [{ "name" => plan[:model][:name], "context_limit" => plan[:model][:context_limit] }]
430
+ }.compact
431
+ end
432
+
433
+ def spec_endpoint(plan)
434
+ if plan[:type] == "openai_compatible"
435
+ Rubik::LLM::OpenAICompatibleProvider.normalize_endpoint(plan[:base_url])
436
+ else
437
+ plan[:base_url]
438
+ end
439
+ end
440
+
441
+ # An interrupt between the provider write and a failed role write
442
+ # leaves an inert-but-valid provider; the note carries the exact
443
+ # repair command. Role writes are the only routing-affecting
444
+ # mutations, so they run last.
445
+ def bind_roles(plan)
446
+ failures = []
447
+ plan[:roles].each do |role|
448
+ res = @config.set_model_spec(role, provider: plan[:id], name: plan[:model][:name],
449
+ endpoint: plan[:base_url], persist: @scope)
450
+ next if res[:ok]
451
+
452
+ failures << role
453
+ note("rol '#{role}' yazılamadı — `!model set #{role} #{plan[:id]}/#{plan[:model][:name]}` ile tamamlayın / " \
454
+ "role write failed — complete it with !model set")
455
+ break
456
+ end
457
+ failures
458
+ end
459
+
460
+ def render_success(plan, res, role_failures)
461
+ bound = plan[:roles] - role_failures
462
+ bound_desc = bound.empty? ? "—" : bound.join(", ")
463
+ @io.puts @ui.paint("✔ #{plan[:id]}/#{plan[:model][:name]} bağlandı / connected · roller / roles: #{bound_desc} " \
464
+ "[#{scope_persist_label}]", :success)
465
+
466
+ info = res[:secret]
467
+ if info
468
+ if info[:stored]
469
+ @io.puts " API key stored via #{info[:backend]} secret store; the config file holds only a reference."
470
+ elsif info[:warning]
471
+ @io.puts " Warning: #{info[:warning]}"
472
+ end
473
+ end
474
+ @notes.each { |n| @io.puts " Not / Note: #{n}" }
475
+ end
476
+
477
+ def scope_persist_label
478
+ @scope == :project ? "Project level (.rubik/config.yml)" : "System level (~/.rubik/config.yml)"
479
+ end
480
+
481
+ def host_of(url)
482
+ URI.parse(url.to_s).host.to_s
483
+ rescue URI::Error
484
+ url.to_s
485
+ end
486
+ end
487
+ end
488
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "connect/http"
4
+ require_relative "connect/models_dev"
5
+ require_relative "connect/probes"
6
+ require_relative "connect/prompt_ui"
7
+ require_relative "connect/wizard"
@@ -28,7 +28,10 @@ module Rubik
28
28
  "https://api.openai.com/v1/chat/completions"
29
29
  elsif ["https://api.cline.bot", "https://api.cline.bot/api"].include?(clean)
30
30
  "https://api.cline.bot/api/v1/chat/completions"
31
- elsif clean =~ %r{/v\d+\z}i || clean.end_with?("/api")
31
+ elsif clean =~ %r{/v\d+\z}i || clean.end_with?("/api") || clean.end_with?("/openai")
32
+ # The bare "/openai" tail covers OpenAI-compatible gateway bases
33
+ # that already carry their version segment inside (Gemini's
34
+ # documented .../v1beta/openai compat path lists /chat/completions).
32
35
  "#{clean}/chat/completions"
33
36
  else
34
37
  "#{clean}/v1/chat/completions"
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "base"
4
+ require_relative "../../connect"
5
+
6
+ module Rubik
7
+ module REPL
8
+ module Commands
9
+ # `!connect` — the in-REPL entry to the provider connect wizard.
10
+ # Unlike !provider add's :session default, !connect persists to
11
+ # :global by default: the wizard's purpose is durable setup, and a
12
+ # session-scoped provider silently vanishing on exit would undo the
13
+ # friction reduction this command exists for. --project/--global
14
+ # flags override, exactly like every other config-touching command.
15
+ module Connect
16
+ extend Base
17
+
18
+ USAGE_CONNECT = "Usage: !connect [--project|--global]"
19
+
20
+ def self.register(shell)
21
+ shell.register_command("connect",
22
+ description: "Interactive wizard: add an LLM provider (models.dev catalog, live key check) " \
23
+ "and bind model roles",
24
+ usage: USAGE_CONNECT) do |args, ctx|
25
+ # The wizard has no session tier: an explicit --session/-s would
26
+ # otherwise be silently coerced into the most persistent write
27
+ # the wizard can make. Honest refusal beats silent escalation.
28
+ if args.intersect?(["--session", "-s"])
29
+ ctx.out.puts USAGE_CONNECT
30
+ ctx.out.puts " !connect yalnızca kalıcı kapsamlara yazar; oturum-kapsamı için !provider add kullanın."
31
+ ctx.out.puts " !connect writes persistent scopes only; use !provider add for a session-scoped provider."
32
+ else
33
+ scope, _clean = Base.parse_scope(args)
34
+ scope = :global if scope == :session
35
+ result = invoke(ctx, scope)
36
+ ctx.out.puts USAGE_CONNECT if result[:reason] == :non_interactive
37
+ end
38
+ end
39
+ end
40
+
41
+ # ui:/probe: kwargs are test seams — shell-level tests inject a
42
+ # scripted PromptUI (and stubbed probes) instead of driving
43
+ # TTY::Prompt against a StringIO.
44
+ def self.invoke(ctx, scope, ui: nil, probe: nil)
45
+ ui ||= Rubik::Connect::PromptUI.new(input: ctx.input, output: ctx.out, theme: ctx.theme)
46
+ Rubik::Connect::Wizard.new(config: ctx.config, ui: ui, io: ctx.out, scope: scope,
47
+ refresh: -> { ctx.refresh_llm_registry! }, probe: probe).run
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
@@ -7,6 +7,7 @@ require_relative "commands/session"
7
7
  require_relative "commands/workspace"
8
8
  require_relative "commands/lsp"
9
9
  require_relative "commands/agent"
10
+ require_relative "commands/connect"
10
11
  require_relative "commands/plugins"
11
12
  require_relative "commands/mcp"
12
13
  require_relative "commands/skills"
@@ -26,6 +27,7 @@ module Rubik
26
27
  Workspace,
27
28
  Lsp,
28
29
  Agent,
30
+ Connect,
29
31
  Plugins,
30
32
  Mcp,
31
33
  Skills,
@@ -26,6 +26,7 @@ module Rubik
26
26
  heredoc_delimiter = nil
27
27
  last_line_at = nil
28
28
  print_banner
29
+ maybe_offer_connect_wizard! if respond_to?(:maybe_offer_connect_wizard!)
29
30
  Rubik::REPL::InterruptHandler.with_handler do
30
31
  while @running
31
32
  result = read_and_process_line(multiline_buffer, heredoc_delimiter, last_line_at: last_line_at)
@@ -4,6 +4,8 @@ require_relative "../events"
4
4
  require_relative "../log"
5
5
  require_relative "../platform"
6
6
  require_relative "../storage/layout"
7
+ require_relative "../ui/capability"
8
+ require_relative "../connect"
7
9
  require_relative "../orchestrator/subagent/notices"
8
10
  require_relative "../prompt/conversation_rows"
9
11
  require_relative "pending_notice_queue"
@@ -133,6 +135,43 @@ module Rubik
133
135
  resync_llm_route!
134
136
  end
135
137
 
138
+ # First-run onboarding: after the banner shows "model yapılandırılmamış",
139
+ # offer the connect wizard once when boot could not resolve an LLM
140
+ # client. Opt-in ask (default no — Confirmations#ask_yes_no collapses
141
+ # to the default off live TTYs, so scripted boots are untouched),
142
+ # knob-gated (connect.first_run_offer), once per process, never
143
+ # raises — the same boot-path honesty as sync_default_llm_route.
144
+ def maybe_offer_connect_wizard!
145
+ return if @connect_offer_shown
146
+
147
+ @connect_offer_shown = true
148
+ return unless @config && @output && @input
149
+ return unless respond_to?(:ask_yes_no)
150
+ return unless Rubik::UI::Capability.interactive?(input: @input, output: @output)
151
+ return unless Rubik::Storage::Layout.config_get(@config, "connect.first_run_offer", true)
152
+ return unless llm_client_pending?
153
+
154
+ answer = ask_yes_no("Hiç model sağlayıcısı yapılandırılmamış görünüyor. Bağlantı sihirbazı çalıştırılsın mı? / " \
155
+ "No LLM provider is configured yet. Run the connect wizard?", default: "n")
156
+ return unless ["y", "yes", "evet"].include?(answer.to_s.downcase)
157
+
158
+ ui = Rubik::Connect::PromptUI.new(input: @input,
159
+ output: Rubik::UI::Capability.unwrap_tee(@output) || @output,
160
+ theme: @ui_theme)
161
+ Rubik::Connect::Wizard.new(config: @config, ui: ui, io: @output, scope: :global,
162
+ refresh: -> { refresh_llm_registry! }).run
163
+ rescue StandardError => e
164
+ debug_warn("Connect wizard offer failed: #{e.class}: #{e.message}")
165
+ end
166
+
167
+ # True when boot's default route failed to satisfy the llm_client
168
+ # coeffect — the honest "nothing usable is configured" signal, so a
169
+ # locally-running Ollama user is never offered the wizard.
170
+ def llm_client_pending?
171
+ context = @runtime_manager&.context
172
+ context.respond_to?(:get) ? context.get(:llm_client).nil? : false
173
+ end
174
+
136
175
  # Live LLM re-route (reactive config wiring, !model/!provider switches):
137
176
  # re-open sticky routing so the next free-text turn re-resolves with the
138
177
  # new model (Plan 61 D-7), then re-provide the default llm_client
data/lib/rubik/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Rubik
4
- VERSION = "0.12.0"
4
+ VERSION = "0.13.0"
5
5
  end