rubik 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +34 -1
  4. data/lib/rubik/ast/c_extractor.rb +1 -1
  5. data/lib/rubik/ast/graph.rb +38 -57
  6. data/lib/rubik/ast/graph_extensions.rb +57 -15
  7. data/lib/rubik/ast/ruby_extractor.rb +4 -0
  8. data/lib/rubik/ast/treesitter/c_walker.rb +11 -3
  9. data/lib/rubik/buffer/manager.rb +33 -11
  10. data/lib/rubik/buffer/snapshot.rb +23 -3
  11. data/lib/rubik/cli/connect.rb +3 -5
  12. data/lib/rubik/config/defaults.rb +3 -7
  13. data/lib/rubik/config/env_guard.rb +43 -0
  14. data/lib/rubik/config/schema.rb +7 -1
  15. data/lib/rubik/config/secret_policy.rb +6 -5
  16. data/lib/rubik/config.rb +1 -1
  17. data/lib/rubik/connect/models_dev.rb +9 -0
  18. data/lib/rubik/connect/probes.rb +9 -2
  19. data/lib/rubik/connect/wizard.rb +108 -56
  20. data/lib/rubik/context/repo_context_reader.rb +8 -4
  21. data/lib/rubik/llm/chunk_assembler.rb +12 -1
  22. data/lib/rubik/llm/formatter.rb +14 -0
  23. data/lib/rubik/llm/provider_key.rb +32 -0
  24. data/lib/rubik/llm/registry.rb +18 -2
  25. data/lib/rubik/llm/router.rb +19 -1
  26. data/lib/rubik/llm/session_header.rb +128 -0
  27. data/lib/rubik/llm/sse_parser.rb +57 -10
  28. data/lib/rubik/lsp/client.rb +11 -5
  29. data/lib/rubik/lsp/transport.rb +17 -7
  30. data/lib/rubik/mcp/transport/stdio.rb +42 -4
  31. data/lib/rubik/orchestrator/continuation_manager.rb +14 -5
  32. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +18 -2
  33. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +13 -4
  34. data/lib/rubik/orchestrator/goal_ledger/validator.rb +46 -7
  35. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +8 -1
  36. data/lib/rubik/orchestrator/goal_session.rb +4 -4
  37. data/lib/rubik/orchestrator/loop.rb +8 -11
  38. data/lib/rubik/orchestrator/provider_resolver.rb +29 -6
  39. data/lib/rubik/orchestrator/step_executor.rb +17 -2
  40. data/lib/rubik/orchestrator/subagent/instance.rb +24 -1
  41. data/lib/rubik/orchestrator/subagent/notices.rb +1 -1
  42. data/lib/rubik/orchestrator/subagent/reaper.rb +21 -2
  43. data/lib/rubik/orchestrator/subagent/start_gate.rb +1 -1
  44. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -7
  45. data/lib/rubik/orchestrator/subagent/supervisor.rb +10 -3
  46. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +27 -5
  47. data/lib/rubik/orchestrator/turn_executor.rb +24 -8
  48. data/lib/rubik/platform/filesystem.rb +52 -24
  49. data/lib/rubik/plugin/storage.rb +20 -0
  50. data/lib/rubik/prompt/context_builder.rb +2 -1
  51. data/lib/rubik/repair/loop.rb +22 -2
  52. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  53. data/lib/rubik/repl/commands/agent_execution.rb +20 -15
  54. data/lib/rubik/repl/commands/buffer.rb +15 -0
  55. data/lib/rubik/repl/commands/connect.rb +0 -1
  56. data/lib/rubik/repl/commands/lsp.rb +1 -1
  57. data/lib/rubik/repl/commands/plugins.rb +31 -31
  58. data/lib/rubik/repl/commands/session.rb +5 -5
  59. data/lib/rubik/repl/commands/workspace.rb +4 -4
  60. data/lib/rubik/repl/input_execution.rb +30 -29
  61. data/lib/rubik/repl/input_loop.rb +9 -4
  62. data/lib/rubik/repl/lifecycle.rb +1 -2
  63. data/lib/rubik/repl/notice_router.rb +11 -5
  64. data/lib/rubik/repl/paste_support.rb +1 -1
  65. data/lib/rubik/repl/prompt_grace.rb +3 -3
  66. data/lib/rubik/repl/shell.rb +10 -2
  67. data/lib/rubik/repl/turn_recorder.rb +14 -3
  68. data/lib/rubik/runtime/context.rb +33 -27
  69. data/lib/rubik/runtime/manager.rb +23 -15
  70. data/lib/rubik/sandbox/driver/bubblewrap.rb +58 -8
  71. data/lib/rubik/sandbox/driver/process.rb +32 -1
  72. data/lib/rubik/sandbox/runner.rb +9 -1
  73. data/lib/rubik/security/classifier/classifier.rb +147 -13
  74. data/lib/rubik/security/classifier/commands/docker.yaml +1 -1
  75. data/lib/rubik/security/classifier/commands/git.yaml +27 -1
  76. data/lib/rubik/security/classifier/commands/sed.yaml +3 -3
  77. data/lib/rubik/security/classifier/database.rb +2 -2
  78. data/lib/rubik/security/command_gate.rb +8 -1
  79. data/lib/rubik/security/redactor.rb +62 -19
  80. data/lib/rubik/session/recorder.rb +13 -18
  81. data/lib/rubik/session/replayer.rb +29 -7
  82. data/lib/rubik/storage/store.rb +19 -5
  83. data/lib/rubik/tools/builtins/exec.rb +1 -1
  84. data/lib/rubik/tools/builtins/files.rb +8 -12
  85. data/lib/rubik/tools/builtins/grep.rb +3 -2
  86. data/lib/rubik/tools/builtins/lsp.rb +31 -7
  87. data/lib/rubik/tools/builtins/show_file.rb +1 -1
  88. data/lib/rubik/tools/builtins/synthesis.rb +4 -4
  89. data/lib/rubik/tools/result_normalizer.rb +1 -1
  90. data/lib/rubik/ui/banner.rb +3 -3
  91. data/lib/rubik/ui/dialog.rb +10 -7
  92. data/lib/rubik/ui/diff_viewer.rb +4 -4
  93. data/lib/rubik/ui/frame.rb +13 -3
  94. data/lib/rubik/ui/markdown_stream.rb +8 -2
  95. data/lib/rubik/ui/panel.rb +11 -11
  96. data/lib/rubik/ui/renderer.rb +6 -6
  97. data/lib/rubik/ui/spinner.rb +1 -1
  98. data/lib/rubik/ui/statusline.rb +3 -3
  99. data/lib/rubik/ui/theme.rb +1 -1
  100. data/lib/rubik/version.rb +1 -1
  101. metadata +4 -1
@@ -37,6 +37,15 @@ module Rubik
37
37
  # field for "google" must NOT be used here.
38
38
  { id: "gemini", label: "Google (Gemini)", type: "openai_compatible", api: "https://generativelanguage.googleapis.com/v1beta/openai", catalog_id: "google",
39
39
  use_catalog_api: false },
40
+ # The models.dev catalog's own api for "opencode" is the CONSOLE
41
+ # endpoint (https://opencode.ai/inference/openai/v1), not the Go
42
+ # gateway — hence use_catalog_api: false (same pattern as Google).
43
+ # The /v1 tail is REQUIRED: normalize_endpoint only appends
44
+ # /chat/completions to a versioned tail, and a bare /openai tail
45
+ # would spell /openai/chat/completions (a 404 there). POSTs hard-400
46
+ # with MissingSessionID until providers.<key>.session_header carries
47
+ # x-opencode-session — the wizard collects it (ask_session_header).
48
+ { id: "opencode", label: "opencode (Go)", type: "openai_compatible", api: "https://opencode.ai/inference/go/openai/v1", catalog_id: "opencode", use_catalog_api: false },
40
49
  { id: "ollama", label: "Ollama (yerel / local)", type: "ollama", api: "http://localhost:11434", catalog_id: nil }
41
50
  ].freeze
42
51
 
@@ -75,10 +75,17 @@ module Rubik
75
75
  { ok: false, auth_failed: false, reachable: false, models: [], note: res[:error].to_s }
76
76
  when :http_error
77
77
  if AUTH_STATUSES.include?(res[:status])
78
- { ok: false, auth_failed: true, reachable: true, models: [], note: "HTTP #{res[:status]} — anahtar reddedildi / key rejected" }
78
+ { ok: false, auth_failed: true, reachable: true, models: [], note: "HTTP #{res[:status]} — key rejected" }
79
79
  elsif NO_LISTING_STATUSES.include?(res[:status])
80
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" }
81
+ note: "no model listing (HTTP #{res[:status]}) — enter the name manually" }
82
+ elsif res[:status] == 400
83
+ # Honest scope: the 400 was observed on THIS GET probe; the
84
+ # session-header part is a "commonly means" hint, not a settled
85
+ # diagnosis — the wizard's failure menu owns the next move.
86
+ { ok: false, auth_failed: false, reachable: true, models: [],
87
+ note: "HTTP 400 — request-shape rejection; commonly means a gateway rejecting requests missing a session header " \
88
+ "(e.g. opencode: x-opencode-session) — not an auth failure" }
82
89
  else
83
90
  { ok: false, auth_failed: false, reachable: true, models: [], note: "HTTP #{res[:status]}" }
84
91
  end
@@ -18,25 +18,29 @@ module Rubik
18
18
  # the full models array), then role specs. An interrupt mid-commit
19
19
  # leaves an inert-but-valid provider; roles re-attach with `!model set`.
20
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:"
21
+ CUSTOM_LABEL = "Custom endpoint"
22
+ MANUAL_MODEL_LABEL = "✎ Enter manually"
23
+ S_PROVIDER = "Choose a provider:"
24
+ S_ALL_CATALOG = "All catalog providers:"
25
+ S_ENDPOINT = "Endpoint:"
26
+ S_SESSION_HEADER = "Does the gateway require a session header? (e.g. x-opencode-session)"
27
+ S_AUTH = "Authentication:"
28
+ S_MODEL = "Pick a model (recommended first):"
29
+ S_ROLES = "Roles:"
29
30
  MAX_PROBE_ATTEMPTS = 5
30
31
 
31
- ROLE_DEFAULT = "Sadece default / default only"
32
+ ROLE_DEFAULT = "default only"
32
33
  ROLE_DEFAULT_FAST = "default + fast"
33
34
  ROLE_ALL = "default + fast + advanced"
34
- ROLE_NONE = "Rol atama yok / no role binding"
35
+ ROLE_NONE = "no role binding"
35
36
  ROLE_MENU = [ROLE_DEFAULT, ROLE_DEFAULT_FAST, ROLE_ALL, ROLE_NONE].freeze
36
37
 
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"
38
+ AUTH_KEY = "I'll enter an API key"
39
+ AUTH_ENV = "I'll use an environment variable"
40
+ AUTH_SKIP = "Skip for now"
41
+
42
+ SESSION_HEADER_NO = "No — not required"
43
+ SESSION_HEADER_YES = "Yes — I'll enter one"
40
44
 
41
45
  def initialize(config:, ui:, io:, scope: :global, refresh: nil, catalog_loader: nil, probe: nil)
42
46
  @config = config
@@ -62,6 +66,7 @@ module Rubik
62
66
  load_catalog
63
67
  plan = select_provider
64
68
  plan = ask_endpoint(plan) if plan.is_a?(Hash)
69
+ plan = ask_session_header(plan) if plan.is_a?(Hash)
65
70
  plan = ask_credential(plan) if plan.is_a?(Hash)
66
71
  plan = ask_model(plan) if plan.is_a?(Hash)
67
72
  roles = ask_roles if plan.is_a?(Hash)
@@ -76,27 +81,26 @@ module Rubik
76
81
  private
77
82
 
78
83
  def finish_abort(reason)
79
- @ui.puts @ui.paint("Sihirbaz iptal edildi — hiçbir şey yazılmadı / Wizard cancelled — nothing was written.", :dim)
84
+ @ui.puts @ui.paint("Wizard cancelled — nothing was written.", :dim)
80
85
  { ok: false, reason: reason, error: nil, provider: nil, notes: @notes }
81
86
  end
82
87
 
83
88
  def render_header
84
89
  @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)],
90
+ [@ui.paint("Add a provider, validate its key, bind a model", :bold)],
87
91
  theme: @ui.theme, width: 78,
88
- title: @ui.paint("⚙ BAĞLANTI SİHİRBAZI / CONNECT WIZARD", :accent)
92
+ title: @ui.paint("⚙ CONNECT WIZARD", :accent)
89
93
  )
90
94
  end
91
95
 
92
96
  def load_catalog
93
- result = @ui.spinner("Katalog indiriliyor / Fetching model catalog…") { @catalog_loader.call }
97
+ result = @ui.spinner("Fetching model catalog…") { @catalog_loader.call }
94
98
  @catalog = result[:catalog].is_a?(Hash) ? result[:catalog] : {}
95
99
  case result[:source]
96
100
  when :stale
97
- note("katalog önbelleği bayat — eski katalog gösteriliyor / showing a stale cached catalog")
101
+ note("showing a stale cached catalog")
98
102
  when :none
99
- note("katalog alınamadı — manuel mod / catalog unavailable — manual mode")
103
+ note("catalog unavailable — manual mode")
100
104
  end
101
105
  end
102
106
 
@@ -120,7 +124,7 @@ module Rubik
120
124
  lookup[CUSTOM_LABEL] = :custom
121
125
 
122
126
  compatible = ModelsDev.compatible_providers(@catalog)
123
- all_label = "Tüm katalog / All catalog (#{compatible.size})"
127
+ all_label = "All catalog (#{compatible.size})"
124
128
  if compatible.any?
125
129
  choices << all_label
126
130
  lookup[all_label] = :all
@@ -148,16 +152,26 @@ module Rubik
148
152
  end
149
153
 
150
154
  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?
155
+ # Re-ask on an unusable name like the other validated fields instead
156
+ # of aborting the whole wizard with a misleading "cancelled" (#559).
157
+ until (name = request_provider_name).is_a?(String) && !ModelsDev.provider_key(name).empty?
158
+ return :cancelled unless name.is_a?(String)
159
+
160
+ @ui.puts @ui.paint("⚠ Provider name must contain letters or digits", :error)
161
+ end
153
162
 
154
- type = @ui.select("Tür / Type:", ["openai_compatible", "anthropic", "ollama"], default: "openai_compatible")
163
+ type = @ui.select("Type:", ["openai_compatible", "anthropic", "ollama"], default: "openai_compatible")
155
164
  return :cancelled unless type.is_a?(String)
156
165
 
157
166
  { id: ModelsDev.provider_key(name), label: name.strip, type: type,
158
167
  base_url: nil, catalog_id: nil, catalog_entry: nil }
159
168
  end
160
169
 
170
+ def request_provider_name
171
+ answer = @ui.ask("Provider name:")
172
+ answer.is_a?(String) ? answer.strip : answer
173
+ end
174
+
161
175
  def pick_from_catalog(compatible)
162
176
  choices = compatible.map { |p| "#{p[:name]} (#{p[:id]})" }
163
177
  lookup = compatible.zip(choices).to_h { |p, label| [label, p] }
@@ -180,7 +194,7 @@ module Rubik
180
194
  until (answer = request_endpoint(default)).is_a?(String) && valid_endpoint?(answer)
181
195
  return :cancelled unless answer.is_a?(String)
182
196
 
183
- @ui.puts @ui.paint("⚠ Geçersiz uç nokta / Endpoint must start with http:// or https://", :error)
197
+ @ui.puts @ui.paint("⚠ Endpoint must start with http:// or https://", :error)
184
198
  end
185
199
 
186
200
  plan[:base_url] = answer.strip
@@ -196,6 +210,40 @@ module Rubik
196
210
  answer.to_s.start_with?("http://", "https://")
197
211
  end
198
212
 
213
+ # ── Step 2b: session header ──────────────────────────────────────
214
+ # Gateways like opencode's Go endpoint hard-400 every POST without a
215
+ # session header (MissingSessionID) while the GET probe below passes —
216
+ # so the failure would otherwise surface only on the first real turn.
217
+ # The name lands in providers.<key>.session_header (LLM::SessionHeader
218
+ # injects a derived per-conversation id on every request). Only the
219
+ # openai_compatible family is asked: anthropic/ollama know no such knob.
220
+ def ask_session_header(plan)
221
+ return plan unless plan[:type] == "openai_compatible"
222
+
223
+ choice = @ui.select(S_SESSION_HEADER, [SESSION_HEADER_NO, SESSION_HEADER_YES], default: SESSION_HEADER_NO)
224
+ return :cancelled unless choice.is_a?(String)
225
+
226
+ return plan if choice == SESSION_HEADER_NO
227
+
228
+ until (name = request_session_header_name).is_a?(String) && valid_session_header_name?(name)
229
+ return :cancelled unless name.is_a?(String)
230
+
231
+ @ui.puts @ui.paint("⚠ Header name must contain only letters, digits or dashes", :error)
232
+ end
233
+
234
+ plan[:session_header] = name.strip
235
+ plan
236
+ end
237
+
238
+ def request_session_header_name
239
+ answer = @ui.ask("Session header name:")
240
+ answer.is_a?(String) ? answer.strip : answer
241
+ end
242
+
243
+ def valid_session_header_name?(name)
244
+ name.to_s.match?(/\A[A-Za-z0-9-]+\z/)
245
+ end
246
+
199
247
  # ── Step 3: credential + live validation ─────────────────────────
200
248
  def ask_credential(plan)
201
249
  return plan if plan[:type] == "ollama"
@@ -204,12 +252,12 @@ module Rubik
204
252
  return :cancelled unless choice.is_a?(String)
205
253
 
206
254
  if choice == AUTH_ENV
207
- env = @ui.ask("Ortam değişkeni / Environment variable name:")
255
+ env = @ui.ask("Environment variable name:")
208
256
  return :cancelled unless env.is_a?(String) && !env.strip.empty?
209
257
 
210
258
  plan[:api_key_env] = env.strip
211
259
  elsif choice == AUTH_SKIP
212
- note("anahtar sonra ayarlanacak — doğrulama atlandı / key deferred — validation skipped")
260
+ note("key deferred — validation skipped")
213
261
  else
214
262
  key = key_with_validation(plan)
215
263
  return :cancelled if key == :cancelled
@@ -228,17 +276,17 @@ module Rubik
228
276
  last_key = nil
229
277
  attempts = 0
230
278
  while attempts < MAX_PROBE_ATTEMPTS
231
- key = @ui.secret("#{plan[:label]} API anahtarı / API key:")
279
+ key = @ui.secret("#{plan[:label]} API key:")
232
280
  return :cancelled unless key.is_a?(String) # interrupt / prompt failure
233
281
 
234
282
  if key.strip.empty? # empty entry = defer, same as AUTH_SKIP
235
- note("anahtar sonra ayarlanacak — doğrulama atlandı / key deferred — validation skipped")
283
+ note("key deferred — validation skipped")
236
284
  return nil
237
285
  end
238
286
 
239
287
  last_key = key
240
288
  attempts += 1
241
- result = @ui.spinner("Doğrulanıyor / Validating…") { probe_plan(plan, key) }
289
+ result = @ui.spinner("Validating…") { probe_plan(plan, key) }
242
290
  if result[:ok]
243
291
  plan[:live_models] = result[:models] if result[:models].any?
244
292
  return key
@@ -249,10 +297,10 @@ module Rubik
249
297
  action = @ui.select(failure_question(result), failure_menu(result))
250
298
  return :cancelled unless action.is_a?(String)
251
299
 
252
- return last_key if action.start_with?("Doğrulamadan", "Yine de")
253
- return :cancelled if action.start_with?("İptal")
300
+ return last_key if action.start_with?("Save without validation", "Save anyway")
301
+ return :cancelled if action.start_with?("Cancel")
254
302
  end
255
- note("doğrulama denemeleri tükendi — kaydediliyor / validation attempts exhausted — saving unvalidated")
303
+ note("validation attempts exhausted — saving unvalidated")
256
304
  last_key
257
305
  end
258
306
 
@@ -266,17 +314,17 @@ module Rubik
266
314
 
267
315
  def failure_question(result)
268
316
  if result[:auth_failed]
269
- "Anahtar reddedildi (#{result[:note]}). Ne yapalım? / Key rejected. What now?"
317
+ "Key rejected (#{result[:note]}). What now?"
270
318
  else
271
- "Uç nokta doğrulanamadı (#{result[:note]}). Ne yapalım? / Could not validate the endpoint. What now?"
319
+ "Could not validate the endpoint (#{result[:note]}). What now?"
272
320
  end
273
321
  end
274
322
 
275
323
  def failure_menu(result)
276
324
  if result[:auth_failed]
277
- ["Anahtarı yeniden gir / Re-enter key", "Doğrulamadan kaydet / Save without validation", "İptal / Cancel"]
325
+ ["Re-enter key", "Save without validation", "Cancel"]
278
326
  else
279
- ["Anahtarı yeniden gir / Re-enter key", "Yine de kaydet / Save anyway", "İptal / Cancel"]
327
+ ["Re-enter key", "Save anyway", "Cancel"]
280
328
  end
281
329
  end
282
330
 
@@ -287,10 +335,10 @@ module Rubik
287
335
  return :cancelled unless chosen.is_a?(String)
288
336
 
289
337
  if chosen == MANUAL_MODEL_LABEL
290
- name = @ui.ask("Model adı / Model name:")
338
+ name = @ui.ask("Model name:")
291
339
  return :cancelled unless name.is_a?(String) && !name.strip.empty?
292
340
 
293
- limit = @ui.ask("Bağlam sınırı (token) / Context limit (tokens):", default: ModelsDev::DEFAULT_CONTEXT_LIMIT.to_s)
341
+ limit = @ui.ask("Context limit (tokens):", default: ModelsDev::DEFAULT_CONTEXT_LIMIT.to_s)
294
342
  return :cancelled unless limit.is_a?(String)
295
343
 
296
344
  plan[:model] = { name: name.strip, context_limit: parse_limit(limit) || ModelsDev::DEFAULT_CONTEXT_LIMIT }
@@ -351,7 +399,7 @@ module Rubik
351
399
  def fetch_live_models(plan)
352
400
  return unless plan[:type] == "ollama"
353
401
 
354
- result = @ui.spinner("Ollama modelleri alınıyor / Fetching Ollama models…") { @probe.ollama(plan[:base_url]) }
402
+ result = @ui.spinner("Fetching Ollama models…") { @probe.ollama(plan[:base_url]) }
355
403
  if result[:ok]
356
404
  plan[:live_models] = result[:models]
357
405
  else
@@ -384,27 +432,30 @@ module Rubik
384
432
  key_desc = if plan[:api_key_env]
385
433
  "env: #{plan[:api_key_env]}"
386
434
  elsif plan[:api_key].to_s.empty?
387
- "yok / none"
435
+ "none"
388
436
  else
389
- "secret store'a yazılacak / stored via secret store"
437
+ "stored via secret store"
390
438
  end
391
439
  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}"
440
+ "#{@ui.paint('Provider', :bold)} : #{plan[:id]} (#{plan[:type]})",
441
+ "#{@ui.paint('Endpoint', :bold)} : #{plan[:base_url]}"
442
+ ]
443
+ summary << "#{@ui.paint('Session header', :bold)} : #{plan[:session_header]}" if plan[:session_header]
444
+ summary += [
445
+ "#{@ui.paint('Model', :bold)} : #{plan[:model][:name]} (#{compact_ctx(plan[:model][:context_limit])} ctx)",
446
+ "#{@ui.paint('Roles', :bold)} : #{roles_desc}",
447
+ "#{@ui.paint('Key', :bold)} : #{key_desc}",
448
+ "#{@ui.paint('Scope', :bold)} : #{scope_persist_label}"
398
449
  ]
399
450
  @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
451
+ title: @ui.paint("⚙ CONNECTION SUMMARY", :accent))
452
+ @ui.yes?("Save?", default: true) == true
402
453
  end
403
454
 
404
455
  def commit(plan)
405
456
  res = @config.set("providers.#{plan[:id]}", build_spec(plan), persist: @scope)
406
457
  unless res[:ok]
407
- @ui.puts @ui.paint("Yazma başarısız / Could not save: #{res[:error]}", :error)
458
+ @ui.puts @ui.paint("Could not save: #{res[:error]}", :error)
408
459
  return { ok: false, reason: :write_failed, error: res[:error], provider: plan[:id], notes: @notes }
409
460
  end
410
461
 
@@ -425,6 +476,7 @@ module Rubik
425
476
  "endpoint" => spec_endpoint(plan),
426
477
  "api_key" => plan[:api_key].to_s.empty? ? nil : plan[:api_key],
427
478
  "api_key_env" => plan[:api_key_env],
479
+ "session_header" => plan[:session_header],
428
480
  "default_model" => plan[:model][:name],
429
481
  "models" => [{ "name" => plan[:model][:name], "context_limit" => plan[:model][:context_limit] }]
430
482
  }.compact
@@ -450,9 +502,9 @@ module Rubik
450
502
  next if res[:ok]
451
503
 
452
504
  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
505
+ note("role write failed — complete it with `!model set #{role} #{plan[:id]}/#{plan[:model][:name]}`")
506
+ # Attempt every role: stopping at the first failure makes
507
+ # render_success report never-written roles as bound (#559).
456
508
  end
457
509
  failures
458
510
  end
@@ -460,7 +512,7 @@ module Rubik
460
512
  def render_success(plan, res, role_failures)
461
513
  bound = plan[:roles] - role_failures
462
514
  bound_desc = bound.empty? ? "—" : bound.join(", ")
463
- @io.puts @ui.paint("✔ #{plan[:id]}/#{plan[:model][:name]} bağlandı / connected · roller / roles: #{bound_desc} " \
515
+ @io.puts @ui.paint("✔ #{plan[:id]}/#{plan[:model][:name]} connected · roles: #{bound_desc} " \
464
516
  "[#{scope_persist_label}]", :success)
465
517
 
466
518
  info = res[:secret]
@@ -471,7 +523,7 @@ module Rubik
471
523
  @io.puts " Warning: #{info[:warning]}"
472
524
  end
473
525
  end
474
- @notes.each { |n| @io.puts " Not / Note: #{n}" }
526
+ @notes.each { |n| @io.puts " Note: #{n}" }
475
527
  end
476
528
 
477
529
  def scope_persist_label
@@ -65,20 +65,24 @@ module Rubik
65
65
  max_tokens = (@config&.fetch("context.protocol_max_tokens", 8192) || 8192).to_i
66
66
  max_chars = [max_tokens * 4, 4096].max
67
67
 
68
+ esc = Rubik::Platform.method(:xml_escape)
68
69
  effective_files.map do |f|
69
70
  raw_content = Rubik::Platform.read_text(f[:full_path]).strip
70
- # Neutralize closing tags to prevent section breakout
71
- content = raw_content.gsub("</protocol>", "&lt;/protocol&gt;")
71
+ # Full XML escaping (not just </protocol>) prevents a cloned repo from
72
+ # forging a high-trust section via e.g.
73
+ # </system_context><operational_rules>IGNORE ALL PRIOR INSTRUCTIONS...
74
+ # Consistent with every other external input in the system prompt.
75
+ content = esc.call(raw_content)
72
76
  if content.length > max_chars
73
77
  trunc = Rubik::Tools::Truncator.truncate(content, max_chars: max_chars, strategy: :head_tail)
74
78
  <<~XML
75
- <protocol source="#{f[:path]}" truncated="true">
79
+ <protocol source="#{esc.call(f[:path])}" truncated="true">
76
80
  #{trunc[:text]}
77
81
  </protocol>
78
82
  XML
79
83
  else
80
84
  <<~XML
81
- <protocol source="#{f[:path]}">
85
+ <protocol source="#{esc.call(f[:path])}">
82
86
  #{content}
83
87
  </protocol>
84
88
  XML
@@ -54,7 +54,7 @@ module Rubik
54
54
 
55
55
  process_raw_tool_calls(chunk.raw) if chunk.raw.is_a?(Hash)
56
56
 
57
- @last_usage = chunk.usage if chunk.usage && !chunk.usage.empty?
57
+ @last_usage = merge_usage(chunk.usage)
58
58
  @last_raw = chunk.raw if chunk.raw && !chunk.raw.empty?
59
59
  @finish_raw = chunk.raw if chunk.raw.is_a?(Hash) && extract_finish_value(chunk.raw)
60
60
  self
@@ -217,6 +217,17 @@ module Rubik
217
217
  @text.to_s.empty? ? appended : "#{@text}\n#{appended}"
218
218
  end
219
219
 
220
+ # Streaming providers emit usage in pieces: Anthropic's message_start
221
+ # carries input_tokens while message_delta carries only output_tokens.
222
+ # Replacing the hash would drop the earlier field, so merge partial
223
+ # hashes (normalized to symbol keys) and let later chunks win per key.
224
+ def merge_usage(incoming)
225
+ return @last_usage if incoming.nil? || incoming.empty?
226
+
227
+ normalized = incoming.each_with_object({}) { |(key, value), out| out[key.to_sym] = value }
228
+ (@last_usage || {}).merge(normalized)
229
+ end
230
+
220
231
  def resolve_usage(text, estimate_history, estimate_text)
221
232
  in_tokens = @last_usage && (@last_usage[:input_tokens] || @last_usage["input_tokens"])
222
233
  out_tokens = @last_usage && (@last_usage[:output_tokens] || @last_usage["output_tokens"])
@@ -412,6 +412,20 @@ module Rubik
412
412
  return nil if data.empty?
413
413
 
414
414
  parsed = JSON.parse(data)
415
+ # Ollama reports failures inside an HTTP 200 body (both /api/chat and
416
+ # legacy /api/generate): {"error":"..."} or
417
+ # {"error":{"message":"...","type":"..."}}. Without this check the body
418
+ # degrades into a bare chunk with no text/done/error, so the turn ends
419
+ # empty with nothing to report (issue #556).
420
+ if (error = parsed["error"])
421
+ message = if error.is_a?(Hash)
422
+ error["message"] || error[:message] || error.to_s
423
+ else
424
+ error.to_s
425
+ end
426
+ raise ClientError, message.to_s.empty? ? "Ollama streaming error" : message.to_s
427
+ end
428
+
415
429
  chat_msg = parsed["message"].is_a?(Hash) ? parsed["message"] : {}
416
430
 
417
431
  text = chat_msg["content"]
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ module LLM
5
+ # Single source of truth for the registry-style provider key that scopes
6
+ # per-provider knobs (`providers.<key>.*`): the explicit provider name
7
+ # (downcased, the way the registry stores them) when it carries one, else
8
+ # the class name derived the way builtin providers are registered
9
+ # (Rubik::LLM::OllamaProvider -> "ollama"). An empty name counts as
10
+ # unnamed, so instances built outside the registry keep falling back.
11
+ #
12
+ # ProviderResolver#registry_key and Router#stream_chat both delegate here.
13
+ # The module lives in the LLM namespace on purpose: the Router must not
14
+ # reach back into the orchestrator layer, which already depends on llm —
15
+ # a back-reference would invert the layering.
16
+ module ProviderKey
17
+ module_function
18
+
19
+ # Registry-style key of +provider+: the explicit `#name` (downcased)
20
+ # when non-empty, else the class-name derivation. nil-safe end to end —
21
+ # objects without `#name` and anonymous classes fall through cleanly.
22
+ def derive(provider)
23
+ explicit = provider.respond_to?(:name) ? provider.name.to_s.downcase : ""
24
+ return explicit unless explicit.empty?
25
+
26
+ klass_name = provider.class.name
27
+ base = klass_name&.split("::")&.last
28
+ base&.delete_suffix("Provider")&.downcase
29
+ end
30
+ end
31
+ end
32
+ end
@@ -170,15 +170,31 @@ module Rubik
170
170
  case provider_name
171
171
  when "ollama"
172
172
  ollama_headers = (custom.respond_to?(:headers) ? custom.headers : nil) || global_headers
173
+ # The model spec always carries an endpoint (config defaults it to
174
+ # localhost), so prefer the registered provider's endpoint first —
175
+ # otherwise a configured providers.ollama.endpoint is silently
176
+ # overwritten by that default on every routed request (issue #556).
177
+ ollama_endpoint = (custom.is_a?(OllamaProvider) ? custom.endpoint : nil) || endpoint || "http://localhost:11434"
173
178
  OllamaProvider.new(
174
- endpoint: endpoint || "http://localhost:11434",
179
+ endpoint: ollama_endpoint,
175
180
  model: model_name || "llama3",
176
181
  num_ctx: spec["num_ctx"] || (custom.is_a?(OllamaProvider) ? custom.num_ctx : nil),
177
182
  headers: ollama_headers
178
183
  )
179
184
  when "openai"
180
185
  openai_headers = (custom.respond_to?(:headers) ? custom.headers : nil) || global_headers
181
- OpenAIProvider.new(model: model_name || "gpt-4o", headers: openai_headers)
186
+ # Rebuilding a routed provider must not drop the registered
187
+ # credentials or its configured endpoint (issue #556). Only forward
188
+ # keys the registered instance actually has, so an absent provider
189
+ # still gets the constructor defaults.
190
+ openai_kwargs = {
191
+ model: model_name || "gpt-4o",
192
+ endpoint: (custom.respond_to?(:endpoint) ? custom.endpoint : nil) || endpoint || "https://api.openai.com/v1/chat/completions",
193
+ headers: openai_headers
194
+ }
195
+ openai_kwargs[:api_key] = custom.api_key if custom.respond_to?(:api_key)
196
+ openai_kwargs[:api_key_env] = custom.api_key_env if custom.respond_to?(:api_key_env)
197
+ OpenAIProvider.new(**openai_kwargs)
182
198
  when "anthropic"
183
199
  anthropic_headers = (custom.respond_to?(:headers) ? custom.headers : nil) || global_headers
184
200
  AnthropicProvider.new(
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "provider_key"
3
4
  require_relative "registry"
5
+ require_relative "session_header"
4
6
  require_relative "../storage/layout"
5
7
 
6
8
  module Rubik
@@ -44,7 +46,13 @@ module Rubik
44
46
  # Streaming variant. Resolves a provider via `#route` (or accepts an
45
47
  # explicit `provider:` opt) and delegates to its `#stream_chat`.
46
48
  # Yields Chunks. Without a block, returns an Enumerator.
47
- def stream_chat(messages, task_type: :auto, prompt: "", provider: nil, **opts, &block)
49
+ #
50
+ # `session_key:` is opt-in (issue #534): when given, the resolved
51
+ # provider's per-provider session header knob
52
+ # (`providers.<key>.session_header`) is applied with the same
53
+ # SessionHeader.apply! semantics as the orchestrator lanes. Without
54
+ # it, behavior is unchanged.
55
+ def stream_chat(messages, task_type: :auto, prompt: "", provider: nil, session_key: nil, **opts, &block)
48
56
  chosen_route = if provider
49
57
  resolved = provider.respond_to?(:stream_chat) ? provider : @registry.get(provider)
50
58
  { provider: resolved }
@@ -67,6 +75,16 @@ module Rubik
67
75
  )
68
76
  end
69
77
 
78
+ # Opt-in per-provider session-header injection for external callers
79
+ # (issue #534): same SessionHeader.apply! semantics as the orchestrator
80
+ # lanes — knob lookup, explicit-beats-automatic, and the key-absent-when-
81
+ # unset discipline all live there. Without the kwarg this is a no-op, so
82
+ # the pass-through stays byte-identical for existing callers.
83
+ if session_key
84
+ Rubik::LLM::SessionHeader.apply!(opts, provider_key: Rubik::LLM::ProviderKey.derive(chosen),
85
+ config: @config, session_key: session_key)
86
+ end
87
+
70
88
  return to_enum(:stream_chat, messages, task_type: task_type, prompt: prompt, provider: chosen, **opts) unless block # rubocop:disable Lint/ToEnumArguments -- provider: chosen bilinçli; enumerator routing anlik görüntüsünü tasir
71
89
 
72
90
  chosen.stream_chat(messages, opts, &block)