valkyria-cli 0.1.0__py3-none-any.whl

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 (55) hide show
  1. valkyria_cli-0.1.0.dist-info/METADATA +117 -0
  2. valkyria_cli-0.1.0.dist-info/RECORD +55 -0
  3. valkyria_cli-0.1.0.dist-info/WHEEL +4 -0
  4. valkyria_cli-0.1.0.dist-info/entry_points.txt +3 -0
  5. valkyrie/__init__.py +5 -0
  6. valkyrie/auth/__init__.py +21 -0
  7. valkyrie/auth/account.py +245 -0
  8. valkyrie/auth/firebase_config.py +28 -0
  9. valkyrie/auth/login_page.py +177 -0
  10. valkyrie/auth/server.py +145 -0
  11. valkyrie/auth/tokens.py +196 -0
  12. valkyrie/chat/__init__.py +37 -0
  13. valkyrie/chat/clients.py +431 -0
  14. valkyrie/chat/commands.py +229 -0
  15. valkyrie/chat/engine.py +1458 -0
  16. valkyrie/chat/messages.py +108 -0
  17. valkyrie/chat/renderer.py +122 -0
  18. valkyrie/cli/__init__.py +2 -0
  19. valkyrie/cli/auth_commands.py +61 -0
  20. valkyrie/cli/chat_commands.py +139 -0
  21. valkyrie/cli/keys_commands.py +275 -0
  22. valkyrie/cli/main.py +179 -0
  23. valkyrie/cli/model_commands.py +334 -0
  24. valkyrie/cli/rag_commands.py +191 -0
  25. valkyrie/cli/session_commands.py +247 -0
  26. valkyrie/cli/setup_wizard.py +510 -0
  27. valkyrie/core/__init__.py +2 -0
  28. valkyrie/core/cards.py +55 -0
  29. valkyrie/core/config.py +84 -0
  30. valkyrie/core/console.py +122 -0
  31. valkyrie/core/paths.py +68 -0
  32. valkyrie/core/workspace.py +87 -0
  33. valkyrie/providers/__init__.py +23 -0
  34. valkyrie/providers/base.py +78 -0
  35. valkyrie/providers/gemini.py +141 -0
  36. valkyrie/providers/groq.py +102 -0
  37. valkyrie/providers/nvidia.py +95 -0
  38. valkyrie/providers/registry.py +233 -0
  39. valkyrie/rag/__init__.py +32 -0
  40. valkyrie/rag/chunker.py +75 -0
  41. valkyrie/rag/embeddings.py +227 -0
  42. valkyrie/rag/files.py +163 -0
  43. valkyrie/rag/pinecone_store.py +191 -0
  44. valkyrie/rag/pipeline.py +170 -0
  45. valkyrie/sessions/__init__.py +9 -0
  46. valkyrie/sessions/store.py +544 -0
  47. valkyrie/tools/__init__.py +6 -0
  48. valkyrie/tools/local_fs.py +423 -0
  49. valkyrie/tools/registry.py +100 -0
  50. valkyrie/tools/web_search.py +73 -0
  51. valkyrie/vault/__init__.py +26 -0
  52. valkyrie/vault/crypto.py +119 -0
  53. valkyrie/vault/prompt.py +77 -0
  54. valkyrie/vault/store.py +207 -0
  55. valkyrie/vault/sync.py +140 -0
@@ -0,0 +1,1458 @@
1
+ """
2
+ Chat engine — conversation state, context accounting, provider filtering, /model switching, & REPL.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import re
9
+ import sys
10
+ from typing import TYPE_CHECKING
11
+
12
+ import click
13
+ from prompt_toolkit import PromptSession
14
+ from prompt_toolkit.formatted_text import HTML
15
+ from prompt_toolkit.styles import Style
16
+ from rich import box
17
+ from rich.panel import Panel
18
+ from rich.table import Table
19
+ from rich.text import Text
20
+
21
+ from valkyrie.chat.clients import ChatStreamError, stream_chat_completion
22
+ from valkyrie.chat.commands import SlashCommand, SlashCommandRegistry, ValkyrieCompleter
23
+ from valkyrie.chat.messages import (
24
+ ChatMessage,
25
+ ContextBudget,
26
+ MessageRole,
27
+ estimate_messages_tokens,
28
+ )
29
+ from valkyrie.chat.renderer import render_agent_stream
30
+ from valkyrie.core.cards import render_tool_card
31
+ from valkyrie.core.console import (
32
+ console,
33
+ print_error,
34
+ print_info,
35
+ print_kv,
36
+ print_rule,
37
+ print_success,
38
+ print_warning,
39
+ render_meter,
40
+ )
41
+ from valkyrie.core.workspace import detect_workspace_root, list_workspace_files
42
+ from valkyrie.providers.registry import PROVIDERS, ModelRegistry
43
+ from valkyrie.rag.embeddings import resolve_pinecone_api_key
44
+ from valkyrie.rag.files import read_workspace_file
45
+ from valkyrie.rag.pipeline import (
46
+ format_rag_context,
47
+ index_workspace_path,
48
+ search_workspace_rag,
49
+ )
50
+ from valkyrie.tools.registry import AgentToolset
51
+ from valkyrie.tools.web_search import run_duckduckgo_search
52
+
53
+ if TYPE_CHECKING:
54
+ from pathlib import Path
55
+
56
+ from valkyrie.core.config import ValkyrieConfig
57
+ from valkyrie.providers.base import ModelInfo
58
+ from valkyrie.rag.pinecone_store import PineconeRagStore
59
+ from valkyrie.sessions.store import SessionRecord, SessionStore
60
+
61
+ _AT_PATH_RE = re.compile(r"(?<!\S)@([A-Za-z0-9_.\-/]+)")
62
+
63
+ _PROMPT_STYLE = Style.from_dict(
64
+ {
65
+ "completion-menu": "bg:#11161f #c9d1d9",
66
+ "completion-menu.completion": "bg:#11161f #c9d1d9",
67
+ "completion-menu.completion.current": "bg:#00f5d4 #0a0e14 bold",
68
+ "completion-menu.meta": "bg:#11161f #8b949e",
69
+ "completion-menu.meta.current": "bg:#00f5d4 #0a0e14",
70
+ "scrollbar.background": "bg:#0d1117",
71
+ "scrollbar.button": "bg:#30363d",
72
+ "bottom-toolbar": "bg:#0d1117 #8b949e",
73
+ }
74
+ )
75
+
76
+
77
+ def build_system_prompt(
78
+ config: ValkyrieConfig,
79
+ workspace_root: Path | None = None,
80
+ ) -> str:
81
+ """Build an editorial agent system prompt describing available local & web tools."""
82
+ from pathlib import Path as _Path
83
+
84
+ ws_hint = str(workspace_root) if workspace_root else "."
85
+ home_downloads = str(_Path.home() / "Downloads")
86
+ lines = [
87
+ "You are Valkyrie, a precise, capable terminal AI agent.",
88
+ "Keep answers direct, accurate, and formatted cleanly in Markdown.",
89
+ "You have real tools to work on the user's local machine and search the web:",
90
+ "- write_file / edit_file / delete_file / read_file / list_directory / search_files",
91
+ f" (Workspace root: {ws_hint}; user Downloads folder: {home_downloads})",
92
+ "- web_search (live DuckDuckGo search via LangChain)",
93
+ "When the user asks you to create, read, update, change, or delete a file or search "
94
+ "the web, call the appropriate tool(s) immediately and report the exact paths/URLs.",
95
+ ]
96
+ profile_parts: list[str] = []
97
+ if config.profile.name:
98
+ profile_parts.append(f"name={config.profile.name}")
99
+ if config.profile.profession:
100
+ profile_parts.append(f"profession={config.profile.profession}")
101
+ if config.profile.expertise:
102
+ profile_parts.append(f"expertise={config.profile.expertise}")
103
+ if profile_parts:
104
+ lines.append("User context: " + ", ".join(profile_parts) + ".")
105
+ return "\n".join(lines)
106
+
107
+
108
+ _MAX_TOOL_STEPS = 8
109
+
110
+
111
+ class ChatEngine:
112
+ """Manages an interactive chat conversation, model state, tools, and context budget."""
113
+
114
+ def __init__(
115
+ self,
116
+ *,
117
+ config: ValkyrieConfig,
118
+ registry: ModelRegistry,
119
+ api_keys: dict[str, str],
120
+ initial_model: str,
121
+ session_store: SessionStore | None = None,
122
+ session_id: str | None = None,
123
+ initial_messages: list[ChatMessage] | None = None,
124
+ total_prompt_tokens: int = 0,
125
+ total_completion_tokens: int = 0,
126
+ workspace_root: Path | None = None,
127
+ auto_rag: bool = True,
128
+ rag_store: PineconeRagStore | None = None,
129
+ auto_approve_tools: bool | None = None,
130
+ enable_tools: bool = True,
131
+ ) -> None:
132
+ self.config = config
133
+ self.registry = registry
134
+ self.api_keys = api_keys
135
+ self.active_model = initial_model
136
+ self.session_store = session_store
137
+ self.session_id = session_id
138
+ self.workspace_root = workspace_root or detect_workspace_root()
139
+ self.auto_rag = auto_rag
140
+ self.rag_store = rag_store
141
+ self.enable_tools = enable_tools
142
+ self.auto_approve_tools = (
143
+ auto_approve_tools if auto_approve_tools is not None else (not sys.stdin.isatty())
144
+ )
145
+ self.toolset = AgentToolset(
146
+ workspace_root=self.workspace_root,
147
+ confirm_fn=self._confirm_tool_action,
148
+ )
149
+ self.messages: list[ChatMessage] = (
150
+ list(initial_messages)
151
+ if initial_messages
152
+ else [
153
+ ChatMessage(
154
+ role=MessageRole.SYSTEM,
155
+ content=build_system_prompt(config, self.workspace_root),
156
+ )
157
+ ]
158
+ )
159
+ self.total_prompt_tokens = total_prompt_tokens
160
+ self.total_completion_tokens = total_completion_tokens
161
+ self.last_suggested_model: str | None = None
162
+
163
+ def _confirm_tool_action(self, action: str, target: str, preview: str | None) -> bool:
164
+ """Interactive confirmation for local file writes, edits, and deletions."""
165
+ if self.auto_approve_tools or not sys.stdin.isatty():
166
+ return True
167
+
168
+ console.print()
169
+ print_info(f"Agent requests [bold]{action}[/bold] on [bold]{target}[/bold]")
170
+ if preview:
171
+ for line in preview.splitlines()[:8]:
172
+ console.print(f" [dim]{line}[/dim]")
173
+ is_delete = action == "delete_file"
174
+ default_choice = "n" if is_delete else "y"
175
+ prompt_str = " ▸ Allow? [y/N/a(always)]" if is_delete else " ▸ Apply? [Y/n/a(always)]"
176
+ ans = click.prompt(prompt_str, default=default_choice, show_default=False).strip().lower()
177
+ if ans in ("a", "all", "always"):
178
+ self.auto_approve_tools = True
179
+ print_success("Auto-approve enabled for this chat session.")
180
+ return True
181
+ return ans in ("y", "yes")
182
+
183
+ @property
184
+ def provider_and_model(self) -> tuple[str, str]:
185
+ """Split active_model ('provider/model') into (provider, model_id)."""
186
+ if "/" not in self.active_model:
187
+ return "", self.active_model
188
+ provider_key, model_id = self.active_model.split("/", 1)
189
+ return provider_key, model_id
190
+
191
+ def get_budget(self, target_model: str | None = None) -> ContextBudget:
192
+ """Compute current context budget against active or target model."""
193
+ qid = target_model or self.active_model
194
+ info = self.registry.get_model(qid)
195
+ window = info.context_window if info else None
196
+ used = estimate_messages_tokens(self.messages)
197
+ return ContextBudget(
198
+ used_tokens=used,
199
+ context_window=window,
200
+ total_prompt_tokens=self.total_prompt_tokens,
201
+ total_completion_tokens=self.total_completion_tokens,
202
+ )
203
+
204
+ def clear_history(self) -> None:
205
+ """Reset conversation turns while preserving the current session ID."""
206
+ self.messages = [self.messages[0]]
207
+ if self.session_store is not None and self.session_id is not None:
208
+ self.session_store.replace_messages(self.session_id, self.messages)
209
+
210
+ def start_new_session(self, *, title: str | None = None) -> SessionRecord | None:
211
+ """Reset the context window and open a fresh session (preserving any prior session)."""
212
+ sys_msg = ChatMessage(
213
+ role=MessageRole.SYSTEM,
214
+ content=build_system_prompt(self.config, self.workspace_root),
215
+ )
216
+ self.messages = [sys_msg]
217
+ self.total_prompt_tokens = 0
218
+ self.total_completion_tokens = 0
219
+ self.last_suggested_model = None
220
+
221
+ if self.session_store is not None:
222
+ created = self.session_store.create_session(
223
+ active_model=self.active_model,
224
+ workspace_root=str(self.workspace_root),
225
+ title=title,
226
+ initial_messages=[sys_msg],
227
+ )
228
+ self.session_id = created.id
229
+ return created
230
+
231
+ self.session_id = None
232
+ return None
233
+
234
+ def compact_context(self, *, keep_last: int = 4) -> tuple[bool, int, int]:
235
+ """
236
+ Compact older turns into a concise summary message, preserving recent turns.
237
+
238
+ Uses configured `summarization` model if available, falling back to deterministic
239
+ extractive bullets when offline or unconfigured.
240
+ """
241
+ before_count = len(self.messages)
242
+ system_msgs = [m for m in self.messages if m.role == MessageRole.SYSTEM]
243
+ non_system = [m for m in self.messages if m.role != MessageRole.SYSTEM]
244
+ if len(non_system) <= keep_last:
245
+ return False, before_count, before_count
246
+
247
+ older = non_system[:-keep_last] if keep_last > 0 else non_system
248
+ summary_text = self._summarize_messages(older)
249
+
250
+ tail = non_system[-keep_last:] if keep_last > 0 else []
251
+ compacted_msg = ChatMessage(
252
+ role=MessageRole.SYSTEM,
253
+ content=f"[Compacted conversation summary]\n{summary_text}",
254
+ )
255
+ self.messages = [*system_msgs[:1], compacted_msg, *tail]
256
+ if self.session_store is not None and self.session_id is not None:
257
+ self.session_store.replace_messages(self.session_id, self.messages)
258
+ return True, before_count, len(self.messages)
259
+
260
+ def _summarize_messages(self, older: list[ChatMessage]) -> str:
261
+ """Summarize older messages via summarization model or extractive fallback."""
262
+ target_model = self.config.models.summarization or self.active_model
263
+ if "/" in target_model:
264
+ pkey, mid = target_model.split("/", 1)
265
+ api_key = self.api_keys.get(pkey)
266
+ if api_key:
267
+ transcript = "\n".join(f"{m.role.value}: {m.content[:500]}" for m in older)
268
+ prompt = [
269
+ ChatMessage(
270
+ role=MessageRole.SYSTEM,
271
+ content=(
272
+ "Summarize this conversation concisely, preserving key facts, "
273
+ "decisions, and file paths."
274
+ ),
275
+ ),
276
+ ChatMessage(role=MessageRole.USER, content=transcript),
277
+ ]
278
+ try:
279
+ chunks = asyncio.run(
280
+ self._collect_stream_text(
281
+ provider_key=pkey,
282
+ model_id=mid,
283
+ api_key=api_key,
284
+ messages=prompt,
285
+ )
286
+ )
287
+ if chunks.strip():
288
+ return chunks.strip()
289
+ except ChatStreamError:
290
+ pass
291
+
292
+ bullets: list[str] = []
293
+ for msg in older:
294
+ snippet = " ".join(msg.content.split())
295
+ if len(snippet) > 120:
296
+ snippet = snippet[:117] + "..."
297
+ bullets.append(f"- {msg.role.value}: {snippet}")
298
+ return "\n".join(bullets)
299
+
300
+ @staticmethod
301
+ async def _collect_stream_text(
302
+ *,
303
+ provider_key: str,
304
+ model_id: str,
305
+ api_key: str,
306
+ messages: list[ChatMessage],
307
+ ) -> str:
308
+ parts: list[str] = []
309
+ async for chunk in stream_chat_completion(
310
+ provider_key=provider_key,
311
+ model_id=model_id,
312
+ api_key=api_key,
313
+ messages=messages,
314
+ temperature=0.2,
315
+ ):
316
+ if chunk.delta:
317
+ parts.append(chunk.delta)
318
+ return "".join(parts)
319
+
320
+ def switch_model(
321
+ self,
322
+ target_model: str,
323
+ *,
324
+ force_truncate: bool = False,
325
+ persist_default: bool = False,
326
+ ) -> tuple[bool, str]:
327
+ """
328
+ Switch the active session model per §4.3.
329
+
330
+ Accepts <provider>/<model> or a unique bare model ID from the cached catalog.
331
+ Never silently substitutes another model.
332
+ """
333
+ resolved_target = target_model.strip()
334
+ if "/" not in resolved_target:
335
+ if self.registry.models:
336
+ current_provider, _ = self.provider_and_model
337
+ found, suggestions = self.registry.resolve_model(
338
+ resolved_target,
339
+ preferred_provider=current_provider or None,
340
+ )
341
+ if found is not None:
342
+ resolved_target = found.qualified_id
343
+ elif suggestions:
344
+ hint = ", ".join(m.qualified_id for m in suggestions[:3])
345
+ return (
346
+ False,
347
+ f"Multiple or partial matches for '{target_model}': {hint}",
348
+ )
349
+ else:
350
+ return (
351
+ False,
352
+ "Use <provider>/<model_id> format (e.g. groq/llama-3.3-70b-versatile) "
353
+ "or '/model list <provider>' to browse.",
354
+ )
355
+ else:
356
+ return (
357
+ False,
358
+ "Use <provider>/<model_id> format (e.g. groq/llama-3.3-70b-versatile).",
359
+ )
360
+
361
+ provider_key, _ = resolved_target.split("/", 1)
362
+ if provider_key not in PROVIDERS:
363
+ return False, f"Unknown provider '{provider_key}'."
364
+ if provider_key not in self.api_keys:
365
+ return (
366
+ False,
367
+ f"No API key unlocked for '{provider_key}'. "
368
+ f"Add it with 'valkyrie keys add {provider_key}'.",
369
+ )
370
+
371
+ info = self.registry.get_model(resolved_target)
372
+ if self.registry.models and info is None:
373
+ return (
374
+ False,
375
+ f"Model '{resolved_target}' was not found in your catalog. "
376
+ "Run '/model list' to inspect compatible choices.",
377
+ )
378
+ if info is not None and not info.is_active:
379
+ return False, f"Model '{resolved_target}' is marked inactive/retired."
380
+
381
+ target_window = info.context_window if info else None
382
+ budget = self.get_budget(resolved_target)
383
+ if not budget.fits(target_window):
384
+ if not force_truncate:
385
+ return (
386
+ False,
387
+ f"Current context (~{budget.used_tokens:,} tokens) exceeds "
388
+ f"'{resolved_target}' window ({target_window:,} tokens). "
389
+ "Clear or compact history before switching.",
390
+ )
391
+ self.clear_history()
392
+
393
+ self.active_model = resolved_target
394
+ self.last_suggested_model = None
395
+ if self.session_store is not None and self.session_id is not None:
396
+ self.session_store.update_active_model(self.session_id, resolved_target)
397
+ if persist_default:
398
+ self.config.models.chat = resolved_target
399
+ self.config.save()
400
+ return True, f"Switched active model -> {resolved_target}."
401
+
402
+ def _build_turn_context(self, user_text: str) -> ChatMessage | None:
403
+ """Collect @path file attachments and optional Pinecone RAG context for a turn."""
404
+ sections: list[str] = []
405
+
406
+ # 1. Read-only @path attachments inside workspace scope
407
+ seen: set[str] = set()
408
+ for raw_path in _AT_PATH_RE.findall(user_text):
409
+ if raw_path in seen:
410
+ continue
411
+ seen.add(raw_path)
412
+ try:
413
+ res = read_workspace_file(self.workspace_root, raw_path)
414
+ render_tool_card(
415
+ tool="read",
416
+ status="ok",
417
+ target=res.rel_path,
418
+ summary=f"L{res.start_line}-L{res.end_line} of {res.total_lines} lines",
419
+ )
420
+ sections.append(
421
+ f"[File: {res.rel_path} L{res.start_line}-L{res.end_line}]\n{res.content}"
422
+ )
423
+ except PermissionError as exc:
424
+ render_tool_card(tool="read", status="blocked", target=raw_path, summary=str(exc))
425
+ except (FileNotFoundError, ValueError):
426
+ pass
427
+
428
+ # 2. Automatic Pinecone retrieval context injection when configured
429
+ pc_key = resolve_pinecone_api_key(self.workspace_root, self.api_keys)
430
+ if self.auto_rag and (pc_key or self.rag_store is not None):
431
+ try:
432
+ hits, _ = search_workspace_rag(
433
+ user_text,
434
+ self.workspace_root,
435
+ config=self.config,
436
+ api_keys=self.api_keys,
437
+ pinecone_api_key=pc_key,
438
+ store=self.rag_store,
439
+ top_k=3,
440
+ )
441
+ relevant = [h for h in hits if h.score >= 0.25]
442
+ if relevant:
443
+ cites = ", ".join(h.citation for h in relevant)
444
+ render_tool_card(
445
+ tool="rag",
446
+ status="ok",
447
+ target=f"{len(relevant)} Pinecone chunk(s)",
448
+ summary=f"Citations: {cites}",
449
+ )
450
+ sections.append(format_rag_context(relevant))
451
+ except Exception as exc:
452
+ print_warning(f"Pinecone retrieval unavailable: {exc}")
453
+
454
+ if not sections:
455
+ return None
456
+ return ChatMessage(role=MessageRole.SYSTEM, content="\n\n".join(sections))
457
+
458
+ def _handle_stream_error(self, exc: ChatStreamError, provider_key: str) -> None:
459
+ """Render clean diagnostics and deprecated/404 model replacement hints."""
460
+ self.last_suggested_model = None
461
+ err_str = str(exc)
462
+ is_missing_or_retired = (
463
+ exc.status_code == 404
464
+ or "no longer available" in err_str.lower()
465
+ or "deprecated" in err_str.lower()
466
+ or "not found" in err_str.lower()
467
+ )
468
+
469
+ details: str | None = None
470
+ if is_missing_or_retired:
471
+ failing_info = self.registry.get_model(self.active_model)
472
+ if failing_info is not None:
473
+ failing_info.is_active = False
474
+
475
+ alternatives: list[str] = []
476
+ if exc.suggested_model and exc.suggested_model != self.active_model:
477
+ alternatives.append(exc.suggested_model)
478
+
479
+ for m in self.registry.list_models(provider=provider_key, role="chat"):
480
+ if (
481
+ m.is_active
482
+ and m.qualified_id != self.active_model
483
+ and m.qualified_id not in alternatives
484
+ ):
485
+ alternatives.append(m.qualified_id)
486
+ if len(alternatives) >= 4:
487
+ break
488
+
489
+ if not alternatives:
490
+ for pkey in self.api_keys:
491
+ for m in self.registry.list_models(provider=pkey, role="chat"):
492
+ if m.is_active and m.qualified_id != self.active_model:
493
+ alternatives.append(m.qualified_id)
494
+ break
495
+
496
+ if alternatives:
497
+ self.last_suggested_model = alternatives[0]
498
+ alt_lines = "\n".join(f" ▸ /model {alt}" for alt in alternatives)
499
+ details = f"Switch immediately with:\n{alt_lines}\n ▸ /model pick {provider_key}"
500
+
501
+ render_tool_card(
502
+ tool="provider",
503
+ status="error",
504
+ target=self.active_model,
505
+ summary=err_str,
506
+ details=details,
507
+ )
508
+
509
+ async def send_turn(self, user_text: str) -> str | None:
510
+ """Append user message, run agentic tool-calling loop, and update accounting."""
511
+ provider_key, model_id = self.provider_and_model
512
+ api_key = self.api_keys.get(provider_key)
513
+ if not api_key:
514
+ print_error(
515
+ f"No API key available for provider '{provider_key}'. "
516
+ f"Cannot invoke '{self.active_model}'."
517
+ )
518
+ return None
519
+
520
+ extra_ctx = self._build_turn_context(user_text)
521
+ if extra_ctx is not None:
522
+ print_info(
523
+ f"Workspace context attached -> hosted request to [bold]{provider_key}[/bold]."
524
+ )
525
+ user_msg = ChatMessage(role=MessageRole.USER, content=user_text)
526
+ self.messages.append(user_msg)
527
+
528
+ tools_enabled = self.enable_tools
529
+ final_reply: str | None = None
530
+ user_persisted = False
531
+
532
+ for step in range(_MAX_TOOL_STEPS):
533
+ # Insert ephemeral extra_ctx just before the user message on step 0
534
+ if extra_ctx is not None and step == 0:
535
+ request_messages = [*self.messages[:-1], extra_ctx, user_msg]
536
+ else:
537
+ request_messages = self.messages
538
+
539
+ openai_tools = self.toolset.openai_tools() if tools_enabled else None
540
+ gemini_decls = self.toolset.gemini_declarations() if tools_enabled else None
541
+
542
+ try:
543
+ chunks = stream_chat_completion(
544
+ provider_key=provider_key,
545
+ model_id=model_id,
546
+ api_key=api_key,
547
+ messages=request_messages,
548
+ openai_tools=openai_tools,
549
+ gemini_declarations=gemini_decls,
550
+ )
551
+ reply_text, usage, tool_calls = await render_agent_stream(
552
+ chunks,
553
+ qualified_model=self.active_model,
554
+ prompt_messages=request_messages,
555
+ )
556
+ except ChatStreamError as exc:
557
+ err_lower = str(exc).lower()
558
+ if (
559
+ tools_enabled
560
+ and exc.status_code == 400
561
+ and any(k in err_lower for k in ("tool", "function"))
562
+ ):
563
+ tools_enabled = False
564
+ continue
565
+ if step == 0:
566
+ self.messages.pop()
567
+ self._handle_stream_error(exc, provider_key)
568
+ return None
569
+
570
+ self.last_suggested_model = None
571
+ self.total_prompt_tokens += usage.prompt_tokens
572
+ self.total_completion_tokens += usage.completion_tokens
573
+
574
+ if (
575
+ not user_persisted
576
+ and self.session_store is not None
577
+ and self.session_id is not None
578
+ ):
579
+ self.session_store.append_message(self.session_id, user_msg)
580
+ self.session_store.auto_title_if_default(self.session_id, user_text)
581
+ user_persisted = True
582
+
583
+ assistant_msg = ChatMessage(
584
+ role=MessageRole.ASSISTANT,
585
+ content=reply_text,
586
+ model=self.active_model,
587
+ tool_calls=[tc.to_openai_dict() for tc in tool_calls] if tool_calls else None,
588
+ usage=usage,
589
+ )
590
+ self.messages.append(assistant_msg)
591
+ if self.session_store is not None and self.session_id is not None:
592
+ self.session_store.append_message(self.session_id, assistant_msg)
593
+
594
+ if not tool_calls:
595
+ final_reply = reply_text
596
+ break
597
+
598
+ # Execute requested LangChain tools and feed results back
599
+ for tc in tool_calls:
600
+ _, output = self.toolset.execute(tc.name, tc.arguments)
601
+ tool_msg = ChatMessage(
602
+ role=MessageRole.TOOL,
603
+ name=tc.name,
604
+ tool_call_id=tc.id,
605
+ content=output,
606
+ )
607
+ self.messages.append(tool_msg)
608
+ if self.session_store is not None and self.session_id is not None:
609
+ self.session_store.append_message(self.session_id, tool_msg)
610
+
611
+ return final_reply
612
+
613
+
614
+ def build_command_registry(engine: ChatEngine) -> SlashCommandRegistry:
615
+ """Build the slash command registry for an interactive ChatEngine."""
616
+ reg = SlashCommandRegistry(feature_flags=engine.config.feature_flags)
617
+
618
+ def cmd_help(_args: list[str]) -> bool:
619
+ console.print()
620
+ print_rule("Chat Commands")
621
+ for c in reg.help_commands():
622
+ alias_str = f" [dim]({', '.join(c.aliases)})[/dim]" if c.aliases else ""
623
+ label = f"{c.usage}{alias_str}"
624
+ if c.upcoming:
625
+ label += " [dim](upcoming)[/dim]"
626
+ print_kv(label, c.description)
627
+ console.print()
628
+ return True
629
+
630
+ def cmd_model(args: list[str]) -> bool:
631
+ _handle_model_slash(args, engine)
632
+ return True
633
+
634
+ def cmd_budget(_args: list[str]) -> bool:
635
+ budget = engine.get_budget()
636
+ console.print()
637
+ print_kv("Model", f"[model]{engine.active_model}[/model]")
638
+ print_kv("Context", budget.format_summary())
639
+ print_kv(
640
+ "Session totals",
641
+ f"{budget.total_prompt_tokens:,} in · {budget.total_completion_tokens:,} out",
642
+ )
643
+ console.print()
644
+ return True
645
+
646
+ def cmd_clear(_args: list[str]) -> bool:
647
+ engine.clear_history()
648
+ console.clear()
649
+ print_success("Conversation context cleared (session preserved).")
650
+ console.print()
651
+ return True
652
+
653
+ def cmd_new(args: list[str]) -> bool:
654
+ title = " ".join(args).strip() or None
655
+ created = engine.start_new_session(title=title)
656
+ console.clear()
657
+ _render_chat_hud(engine)
658
+ if created is not None:
659
+ print_success(
660
+ f"Started new session [bold]{created.title}[/bold] ([dim]{created.id}[/dim])."
661
+ )
662
+ else:
663
+ print_success("Started new chat context window (ephemeral session).")
664
+ console.print()
665
+ return True
666
+
667
+ def cmd_compact(args: list[str]) -> bool:
668
+ keep = int(args[0]) if args and args[0].isdigit() else 4
669
+ ok, before_cnt, after_cnt = engine.compact_context(keep_last=keep)
670
+ console.print()
671
+ if ok:
672
+ print_success(f"Compacted context: {before_cnt} -> {after_cnt} messages.")
673
+ print_kv("Budget", engine.get_budget().format_summary())
674
+ else:
675
+ print_warning("Not enough messages to compact.")
676
+ console.print()
677
+ return True
678
+
679
+ def cmd_session(_args: list[str]) -> bool:
680
+ console.print()
681
+ print_rule("Current Session")
682
+ print_kv("ID", engine.session_id or "[muted]ephemeral[/muted]")
683
+ if engine.session_store and engine.session_id:
684
+ sess = engine.session_store.get_session(engine.session_id)
685
+ if sess:
686
+ print_kv("Title", sess.title)
687
+ print_kv("Messages", str(sess.message_count))
688
+ if sess.last_checkpoint_id:
689
+ print_kv("Checkpoint", sess.last_checkpoint_id)
690
+ print_kv("Model", f"[model]{engine.active_model}[/model]")
691
+ console.print()
692
+ return True
693
+
694
+ def cmd_workspace(_args: list[str]) -> bool:
695
+ files = list_workspace_files(engine.workspace_root)
696
+ console.print()
697
+ print_rule("Workspace")
698
+ print_kv("Root", str(engine.workspace_root))
699
+ print_kv("Accessible", f"{len(files)} files (use @ to attach)")
700
+ console.print()
701
+ return True
702
+
703
+ def cmd_read(args: list[str]) -> bool:
704
+ if not args:
705
+ print_info("Usage: /read <path> [start_line] [end_line]")
706
+ return True
707
+ raw_path = args[0]
708
+ start_line = int(args[1]) if len(args) >= 2 and args[1].isdigit() else 1
709
+ end_line = int(args[2]) if len(args) >= 3 and args[2].isdigit() else None
710
+ try:
711
+ res = read_workspace_file(
712
+ engine.workspace_root,
713
+ raw_path,
714
+ start_line=start_line,
715
+ end_line=end_line,
716
+ )
717
+ preview_lines = res.content.splitlines()[:12]
718
+ preview = "\n".join(preview_lines)
719
+ if len(res.content.splitlines()) > 12:
720
+ preview += "\n..."
721
+ render_tool_card(
722
+ tool="read",
723
+ status="ok",
724
+ target=res.rel_path,
725
+ summary=f"Read L{res.start_line}-L{res.end_line} of {res.total_lines} lines",
726
+ details=preview,
727
+ )
728
+ except PermissionError as exc:
729
+ render_tool_card(tool="read", status="blocked", target=raw_path, summary=str(exc))
730
+ except (FileNotFoundError, ValueError) as exc:
731
+ render_tool_card(tool="read", status="error", target=raw_path, summary=str(exc))
732
+ return True
733
+
734
+ def cmd_index(args: list[str]) -> bool:
735
+ target = args[0] if args else "."
736
+ pc_key = resolve_pinecone_api_key(engine.workspace_root, engine.api_keys)
737
+ print_info(
738
+ f"Data transfer: indexing '{target}' -> Pinecone DB "
739
+ f"'{engine.config.pinecone.index_name}' (zero local storage)"
740
+ )
741
+ try:
742
+ summary = index_workspace_path(
743
+ engine.workspace_root,
744
+ target,
745
+ config=engine.config,
746
+ api_keys=engine.api_keys,
747
+ pinecone_api_key=pc_key,
748
+ store=engine.rag_store,
749
+ )
750
+ render_tool_card(
751
+ tool="index",
752
+ status="ok",
753
+ target=target,
754
+ summary=(
755
+ f"{summary.files_indexed} files, {summary.chunks_upserted} chunks -> "
756
+ f"{summary.index_name} [{summary.namespace}] ({summary.embedding_backend})"
757
+ ),
758
+ )
759
+ except Exception as exc:
760
+ render_tool_card(tool="index", status="error", target=target, summary=str(exc))
761
+ return True
762
+
763
+ def cmd_search(args: list[str]) -> bool:
764
+ if not args:
765
+ print_info("Usage: /search <query>")
766
+ return True
767
+ query = " ".join(args)
768
+ pc_key = resolve_pinecone_api_key(engine.workspace_root, engine.api_keys)
769
+ try:
770
+ hits, backend = search_workspace_rag(
771
+ query,
772
+ engine.workspace_root,
773
+ config=engine.config,
774
+ api_keys=engine.api_keys,
775
+ pinecone_api_key=pc_key,
776
+ store=engine.rag_store,
777
+ )
778
+ if not hits:
779
+ print_info("No matching chunks found in Pinecone namespace.")
780
+ return True
781
+ lines = [f"▸ {h.citation} ({h.score:.3f})" for h in hits]
782
+ render_tool_card(
783
+ tool="search",
784
+ status="ok",
785
+ target=query,
786
+ summary=f"{len(hits)} Pinecone hit(s) via {backend}",
787
+ details="\n".join(lines),
788
+ )
789
+ except Exception as exc:
790
+ render_tool_card(tool="search", status="error", target=query, summary=str(exc))
791
+ return True
792
+
793
+ def cmd_rag(args: list[str]) -> bool:
794
+ if args and args[0].lower() in ("on", "off"):
795
+ engine.auto_rag = args[0].lower() == "on"
796
+ state = "enabled" if engine.auto_rag else "disabled"
797
+ print_success(f"Auto-RAG Pinecone injection {state}.")
798
+ return True
799
+ pc_key = resolve_pinecone_api_key(engine.workspace_root, engine.api_keys)
800
+ console.print()
801
+ print_kv("Auto-RAG", "on" if engine.auto_rag else "off")
802
+ print_kv("Storage", "Pinecone DB only (app .env configured)")
803
+ print_kv("Pinecone index", engine.config.pinecone.index_name)
804
+ print_kv(
805
+ "Pinecone backend",
806
+ "connected" if (pc_key or engine.rag_store) else "missing in .env",
807
+ )
808
+ console.print()
809
+ return True
810
+
811
+ def cmd_web(args: list[str]) -> bool:
812
+ if not args:
813
+ print_info("Usage: /web <search query>")
814
+ return True
815
+ query = " ".join(args)
816
+ try:
817
+ hits = run_duckduckgo_search(query, max_results=5)
818
+ if not hits:
819
+ print_warning(f"No DuckDuckGo results for '{query}'.")
820
+ return True
821
+ lines = [
822
+ f"▸ [bold]{h['title']}[/bold]\n [dim]{h['link']}[/dim]\n {h['snippet'][:140]}"
823
+ for h in hits
824
+ ]
825
+ render_tool_card(
826
+ tool="web",
827
+ status="ok",
828
+ target=query,
829
+ summary=f"{len(hits)} DuckDuckGo result(s) via LangChain",
830
+ details="\n".join(lines[:3]),
831
+ )
832
+ except Exception as exc:
833
+ render_tool_card(tool="web", status="error", target=query, summary=str(exc))
834
+ return True
835
+
836
+ def cmd_auto(args: list[str]) -> bool:
837
+ if args and args[0].lower() in ("on", "off"):
838
+ engine.auto_approve_tools = args[0].lower() == "on"
839
+ else:
840
+ engine.auto_approve_tools = not engine.auto_approve_tools
841
+ state = (
842
+ "ON (no confirmation prompts)"
843
+ if engine.auto_approve_tools
844
+ else "OFF (prompt before file changes)"
845
+ )
846
+ print_success(f"Tool auto-approve: {state}")
847
+ return True
848
+
849
+ def cmd_account(args: list[str]) -> bool:
850
+ _handle_account_slash(args)
851
+ return True
852
+
853
+ def cmd_exit(_args: list[str]) -> bool:
854
+ print_info("Session closed.")
855
+ return False
856
+
857
+ reg.register(
858
+ SlashCommand("/help", "/help", "List available commands", cmd_help, aliases=("/h", "/?"))
859
+ )
860
+ reg.register(
861
+ SlashCommand(
862
+ "/model",
863
+ "/model [<provider>|ls|pick|rf|<id>]",
864
+ "Inspect, filter by provider, or switch models anytime",
865
+ cmd_model,
866
+ aliases=("/m",),
867
+ )
868
+ )
869
+ reg.register(
870
+ SlashCommand(
871
+ "/budget",
872
+ "/budget",
873
+ "Show context window accounting",
874
+ cmd_budget,
875
+ aliases=("/b",),
876
+ )
877
+ )
878
+ reg.register(
879
+ SlashCommand(
880
+ "/compact",
881
+ "/compact [keep]",
882
+ "Summarize older turns and trim context window",
883
+ cmd_compact,
884
+ aliases=("/cmp",),
885
+ )
886
+ )
887
+ reg.register(
888
+ SlashCommand(
889
+ "/new",
890
+ "/new [title]",
891
+ "Create a new chat session with a fresh context window",
892
+ cmd_new,
893
+ aliases=("/n",),
894
+ )
895
+ )
896
+ reg.register(
897
+ SlashCommand(
898
+ "/clear",
899
+ "/clear",
900
+ "Clear screen and reset conversation context",
901
+ cmd_clear,
902
+ aliases=("/c", "/cls"),
903
+ )
904
+ )
905
+ reg.register(
906
+ SlashCommand(
907
+ "/session",
908
+ "/session",
909
+ "Show active session metadata",
910
+ cmd_session,
911
+ aliases=("/ss",),
912
+ )
913
+ )
914
+ reg.register(
915
+ SlashCommand(
916
+ "/workspace",
917
+ "/workspace",
918
+ "Show workspace root and file count",
919
+ cmd_workspace,
920
+ aliases=("/ws",),
921
+ )
922
+ )
923
+ reg.register(
924
+ SlashCommand(
925
+ "/read",
926
+ "/read <path> [start] [end]",
927
+ "Read a file inside workspace scope",
928
+ cmd_read,
929
+ aliases=("/r",),
930
+ )
931
+ )
932
+ reg.register(
933
+ SlashCommand(
934
+ "/index",
935
+ "/index [path]",
936
+ "Index workspace files into Pinecone DB",
937
+ cmd_index,
938
+ aliases=("/i",),
939
+ )
940
+ )
941
+ reg.register(
942
+ SlashCommand(
943
+ "/search",
944
+ "/search <query>",
945
+ "Search Pinecone workspace index with citations",
946
+ cmd_search,
947
+ aliases=("/s",),
948
+ )
949
+ )
950
+ reg.register(
951
+ SlashCommand(
952
+ "/rag",
953
+ "/rag [on|off|status]",
954
+ "Configure automatic Pinecone RAG context injection",
955
+ cmd_rag,
956
+ )
957
+ )
958
+ reg.register(
959
+ SlashCommand(
960
+ "/web",
961
+ "/web <query>",
962
+ "Search the live web with DuckDuckGo via LangChain",
963
+ cmd_web,
964
+ aliases=("/w",),
965
+ )
966
+ )
967
+ reg.register(
968
+ SlashCommand(
969
+ "/auto",
970
+ "/auto [on|off]",
971
+ "Toggle auto-approval for local file write/edit/delete",
972
+ cmd_auto,
973
+ aliases=("/a",),
974
+ )
975
+ )
976
+ reg.register(
977
+ SlashCommand(
978
+ "/account",
979
+ "/account [st|sw|del|in|out]",
980
+ "Inspect, switch, or delete your signed-in account",
981
+ cmd_account,
982
+ aliases=("/acc", "/auth"),
983
+ )
984
+ )
985
+ reg.register(
986
+ SlashCommand("/exit", "/exit", "Exit chat", cmd_exit, aliases=("/q", "/quit"))
987
+ )
988
+
989
+ # Upcoming Beta capabilities — hidden from normal help, non-executable
990
+ reg.register(
991
+ SlashCommand(
992
+ "/plan",
993
+ "/plan <goal>",
994
+ "Create a step-by-step execution plan before editing",
995
+ upcoming=True,
996
+ )
997
+ )
998
+ return reg
999
+
1000
+
1001
+ def _handle_slash_command(
1002
+ raw: str,
1003
+ engine: ChatEngine,
1004
+ registry: SlashCommandRegistry | None = None,
1005
+ ) -> bool:
1006
+ """
1007
+ Handle an in-chat slash command.
1008
+
1009
+ Returns False if the REPL should exit, True otherwise.
1010
+ """
1011
+ reg = registry or build_command_registry(engine)
1012
+ parts = raw.strip().split()
1013
+ cmd_name = parts[0].lower()
1014
+
1015
+ if cmd_name == "/":
1016
+ for c in reg.executable_commands():
1017
+ print_kv(c.usage, c.description)
1018
+ return True
1019
+
1020
+ cmd = reg.resolve(cmd_name)
1021
+ if cmd is not None and cmd.handler is not None:
1022
+ return cmd.handler(parts[1:])
1023
+
1024
+ matches = reg.filter_prefix(cmd_name)
1025
+ if matches:
1026
+ names = ", ".join(m.name for m in matches)
1027
+ print_warning(f"Ambiguous or partial command '{cmd_name}'. Matches: {names}")
1028
+ else:
1029
+ print_warning(f"Unknown command '{cmd_name}'. Type /help to list commands.")
1030
+ return True
1031
+
1032
+
1033
+ def _render_provider_pills(engine: ChatEngine, active_provider: str | None) -> None:
1034
+ """Render provider filter pills inside chat."""
1035
+ counts = engine.registry.provider_counts()
1036
+ total = sum(counts.values())
1037
+ bar = Text(" FILTER ", style="grey62")
1038
+ if active_provider is None:
1039
+ bar.append(f" ALL ({total}) ", style="bold black on bright_cyan")
1040
+ else:
1041
+ bar.append(f"ALL ({total})", style="grey62")
1042
+
1043
+ for pkey in PROVIDERS:
1044
+ cnt = counts.get(pkey, 0)
1045
+ bar.append(" · ", style="grey35")
1046
+ if active_provider == pkey:
1047
+ bar.append(f" {pkey.upper()} ({cnt}) ", style="bold black on bright_cyan")
1048
+ elif cnt > 0:
1049
+ unlocked = "✓" if pkey in engine.api_keys else "locked"
1050
+ bar.append(f"{pkey} ({cnt})", style="bright_white")
1051
+ if unlocked == "locked":
1052
+ bar.append(" [locked]", style="grey42")
1053
+ else:
1054
+ bar.append(f"{pkey} (0)", style="grey42")
1055
+ console.print(bar)
1056
+
1057
+
1058
+ def _render_model_table(
1059
+ models: list[ModelInfo],
1060
+ *,
1061
+ engine: ChatEngine,
1062
+ provider_filter: str | None,
1063
+ ) -> None:
1064
+ """Display filtered models in a compact editorial Rich table."""
1065
+ console.print()
1066
+ _render_provider_pills(engine, provider_filter)
1067
+ console.print()
1068
+
1069
+ if not models:
1070
+ print_warning("No models match your filter.")
1071
+ console.print()
1072
+ return
1073
+
1074
+ table = Table(
1075
+ box=box.ROUNDED,
1076
+ border_style="rule",
1077
+ header_style="bold bright_white",
1078
+ show_lines=False,
1079
+ pad_edge=True,
1080
+ )
1081
+ table.add_column("#", style="grey50", justify="right", width=3)
1082
+ table.add_column("Model", style="model")
1083
+ table.add_column("Caps", style="bright_cyan")
1084
+ table.add_column("Ctx", justify="right", style="dim")
1085
+ table.add_column("State", justify="right")
1086
+
1087
+ for idx, m in enumerate(models, start=1):
1088
+ caps = " · ".join(c.value for c in m.capabilities)
1089
+ ctx = (
1090
+ f"{m.context_window / 1_000_000:.1f}M"
1091
+ if m.context_window and m.context_window >= 1_000_000
1092
+ else (f"{m.context_window // 1000}k" if m.context_window else "?")
1093
+ )
1094
+ if m.qualified_id == engine.active_model:
1095
+ state = "[tag] ACTIVE [/tag]"
1096
+ elif not m.is_active:
1097
+ state = "[warning]retired[/warning]"
1098
+ elif m.provider not in engine.api_keys:
1099
+ state = "[muted]no key[/muted]"
1100
+ else:
1101
+ state = "[success]ready[/success]"
1102
+ table.add_row(str(idx), m.qualified_id, caps, ctx, state)
1103
+
1104
+ console.print(table)
1105
+ console.print(
1106
+ " [muted]Switch: [bold]/model <provider/id>[/bold] · "
1107
+ "Filter: [bold]/model <groq|gemini|nvidia>[/bold] · "
1108
+ "Pick: [bold]/model pick[/bold][/muted]"
1109
+ )
1110
+ console.print()
1111
+
1112
+
1113
+ def _attempt_model_switch(engine: ChatEngine, target: str) -> None:
1114
+ """Attempt model switch, offering truncate confirmation if context exceeds window."""
1115
+ ok, msg = engine.switch_model(target)
1116
+ if ok:
1117
+ print_success(msg)
1118
+ return
1119
+
1120
+ if "exceeds" in msg:
1121
+ print_warning(msg)
1122
+ if click.confirm(" Clear conversation context and switch anyway?", default=False):
1123
+ ok2, msg2 = engine.switch_model(target, force_truncate=True)
1124
+ if ok2:
1125
+ print_success(msg2)
1126
+ else:
1127
+ print_error(msg2)
1128
+ return
1129
+
1130
+ print_error(msg)
1131
+
1132
+
1133
+ def _interactive_model_picker(engine: ChatEngine, provider_filter: str | None = None) -> None:
1134
+ """Interactive provider-filterable numbered selector inside chat."""
1135
+ current_filter = provider_filter.lower() if provider_filter else None
1136
+ while True:
1137
+ candidates = [
1138
+ m
1139
+ for m in engine.registry.list_models(provider=current_filter, role="chat")
1140
+ if m.is_active
1141
+ ]
1142
+ if not candidates:
1143
+ print_warning("No active chat models available for this filter.")
1144
+ return
1145
+
1146
+ shown = candidates[:15]
1147
+ _render_model_table(shown, engine=engine, provider_filter=current_filter)
1148
+ if len(candidates) > len(shown):
1149
+ print_info(
1150
+ f"Showing top {len(shown)} of {len(candidates)} models. "
1151
+ "Type a provider name (groq/gemini/nvidia) or 'all' to filter."
1152
+ )
1153
+ raw = click.prompt(
1154
+ " Pick # (or provider name, or 'q' to cancel)",
1155
+ default="q",
1156
+ ).strip()
1157
+ lower = raw.lower()
1158
+ if lower in ("q", "quit", "cancel", ""):
1159
+ print_info("Model kept unchanged.")
1160
+ return
1161
+ if lower == "all":
1162
+ current_filter = None
1163
+ continue
1164
+ if lower in PROVIDERS:
1165
+ current_filter = lower
1166
+ continue
1167
+ if raw.isdigit():
1168
+ pos = int(raw) - 1
1169
+ if 0 <= pos < len(shown):
1170
+ _attempt_model_switch(engine, shown[pos].qualified_id)
1171
+ return
1172
+ _attempt_model_switch(engine, raw)
1173
+ return
1174
+
1175
+
1176
+ def _handle_model_slash(args: list[str], engine: ChatEngine) -> None:
1177
+ """
1178
+ Handle /model commands in chat:
1179
+ /model -> active model & role matrix
1180
+ /model <provider> [search] -> filter catalog by provider
1181
+ /model list [provider] [q] -> list full/filtered catalog
1182
+ /model filter <provider> [q] -> filter catalog by provider
1183
+ /model pick [provider] -> interactive numbered switcher
1184
+ /model refresh [provider] -> fetch live models from unlocked providers
1185
+ /model [use] <model_id> -> switch active model immediately
1186
+ """
1187
+ if not args:
1188
+ console.print()
1189
+ print_rule("Session Model")
1190
+ budget = engine.get_budget()
1191
+ print_kv("active", f"[model]{engine.active_model}[/model]")
1192
+ print_kv("budget", budget.format_summary())
1193
+ console.print()
1194
+ for role in ("chat", "code", "planner", "vision", "summarization", "embeddings"):
1195
+ val = getattr(engine.config.models, role, None)
1196
+ print_kv(role, val or "[muted]unassigned[/muted]")
1197
+ console.print()
1198
+ _render_provider_pills(engine, None)
1199
+ console.print(
1200
+ " [muted]Commands: [bold]/model <provider>[/bold] · "
1201
+ "[bold]/model pick[/bold] · [bold]/model <id>[/bold] · "
1202
+ "[bold]/model refresh[/bold][/muted]"
1203
+ )
1204
+ console.print()
1205
+ return
1206
+
1207
+ sub_aliases = {
1208
+ "ls": "list",
1209
+ "f": "filter",
1210
+ "p": "pick",
1211
+ "rf": "refresh",
1212
+ "u": "use",
1213
+ }
1214
+ sub = sub_aliases.get(args[0].lower(), args[0].lower())
1215
+
1216
+ if sub == "refresh":
1217
+ target_p = args[1].lower() if len(args) >= 2 and args[1].lower() in PROVIDERS else None
1218
+ keys = (
1219
+ {target_p: engine.api_keys[target_p]}
1220
+ if target_p and target_p in engine.api_keys
1221
+ else dict(engine.api_keys)
1222
+ )
1223
+ if not keys:
1224
+ print_error("No matching unlocked API keys in this session.")
1225
+ return
1226
+ print_info(f"Refreshing live catalogs for: {', '.join(keys.keys())}…")
1227
+ summary = asyncio.run(engine.registry.refresh(keys))
1228
+ for pkey, (valid, cnt) in summary.items():
1229
+ if valid:
1230
+ print_success(f"{pkey:<10} {cnt} models synced")
1231
+ else:
1232
+ print_warning(f"{pkey:<10} refresh failed")
1233
+ return
1234
+
1235
+ if sub in ("pick", "switch"):
1236
+ p_filter = args[1].lower() if len(args) >= 2 and args[1].lower() in PROVIDERS else None
1237
+ _interactive_model_picker(engine, p_filter)
1238
+ return
1239
+
1240
+ if sub in ("list", "filter") or sub in PROVIDERS:
1241
+ if not engine.registry.models:
1242
+ console.print()
1243
+ print_info("No cached models. Run '/model refresh' or 'valkyrie model refresh'.")
1244
+ console.print()
1245
+ return
1246
+
1247
+ rest = args if sub in PROVIDERS else args[1:]
1248
+ provider_filter: str | None = None
1249
+ search_terms: list[str] = []
1250
+ for token in rest:
1251
+ tok_lower = token.lower()
1252
+ if tok_lower in PROVIDERS and provider_filter is None:
1253
+ provider_filter = tok_lower
1254
+ elif tok_lower not in ("all", "*"):
1255
+ search_terms.append(token)
1256
+
1257
+ search_q = " ".join(search_terms) if search_terms else None
1258
+ models = engine.registry.list_models(provider=provider_filter, search=search_q)
1259
+ _render_model_table(models, engine=engine, provider_filter=provider_filter)
1260
+ return
1261
+
1262
+ if sub == "use":
1263
+ if len(args) < 2:
1264
+ print_info("Usage: /model use <provider/model_id>")
1265
+ return
1266
+ _attempt_model_switch(engine, args[1])
1267
+ return
1268
+
1269
+ # Shorthand: `/model <provider/model_id>` or `/model <bare_model_id>`
1270
+ _attempt_model_switch(engine, args[0])
1271
+
1272
+
1273
+ def _handle_account_slash(args: list[str]) -> None:
1274
+ """
1275
+ Handle /account (and /auth) commands in chat:
1276
+ /account [status] -> inspect current signed-in account
1277
+ /account login -> sign in with Google via browser
1278
+ /account switch -> switch Google account via browser account picker
1279
+ /account delete -> delete signed-in Firebase account & remote vault
1280
+ /account logout -> sign out locally
1281
+ """
1282
+ from valkyrie.auth.account import (
1283
+ delete_account,
1284
+ login_account,
1285
+ logout_account,
1286
+ show_account_status,
1287
+ switch_account,
1288
+ )
1289
+
1290
+ sub_aliases = {
1291
+ "s": "status",
1292
+ "st": "status",
1293
+ "sw": "switch",
1294
+ "del": "delete",
1295
+ "rm": "delete",
1296
+ "in": "login",
1297
+ "out": "logout",
1298
+ }
1299
+ raw_sub = args[0].lower() if args else "status"
1300
+ sub = sub_aliases.get(raw_sub, raw_sub)
1301
+ if sub == "status":
1302
+ show_account_status()
1303
+ console.print(
1304
+ " [muted]Commands: [bold]/account switch[/bold] · "
1305
+ "[bold]/account delete[/bold] · [bold]/account login[/bold] · "
1306
+ "[bold]/account logout[/bold][/muted]"
1307
+ )
1308
+ console.print()
1309
+ return
1310
+
1311
+ if sub == "login":
1312
+ login_account(select_account=False)
1313
+ return
1314
+
1315
+ if sub == "switch":
1316
+ switch_account(interactive=True)
1317
+ return
1318
+
1319
+ if sub == "delete":
1320
+ assume_yes = "--yes" in args[1:]
1321
+ purge_local = "--purge-local" in args[1:]
1322
+ delete_account(assume_yes=assume_yes, purge_local=purge_local)
1323
+ return
1324
+
1325
+ if sub == "logout":
1326
+ logout_account()
1327
+ return
1328
+
1329
+ print_warning(
1330
+ f"Unknown /account action '{sub}'. "
1331
+ "Use: status, switch, delete, login, or logout."
1332
+ )
1333
+
1334
+
1335
+ def _render_chat_hud(engine: ChatEngine) -> None:
1336
+ """Render the responsive startup HUD card for Valkyrie Chat."""
1337
+ budget = engine.get_budget()
1338
+ ratio = (budget.used_tokens / budget.context_window) if budget.context_window else 0.0
1339
+ pc_key = resolve_pinecone_api_key(engine.workspace_root, engine.api_keys)
1340
+ rag_label = (
1341
+ f"[success]Pinecone · {engine.config.pinecone.index_name}[/success]"
1342
+ if (pc_key or engine.rag_store)
1343
+ else "[warning]Pinecone unconfigured[/warning]"
1344
+ )
1345
+
1346
+ grid = Table.grid(expand=True, padding=(0, 2))
1347
+ if console.width >= 76:
1348
+ grid.add_column(ratio=1)
1349
+ grid.add_column(ratio=1)
1350
+ left = Text.from_markup(
1351
+ f"[muted]MODEL[/muted] [model]{engine.active_model}[/model]\n"
1352
+ f"[muted]SESSION[/muted] [dim]{engine.session_id or 'ephemeral'}[/dim]\n"
1353
+ f"[muted]WORKSPACE[/muted] [dim]{engine.workspace_root.name}[/dim]"
1354
+ )
1355
+ pct = f"{ratio * 100:.0f}%" if budget.context_window else "—"
1356
+ right = Text.from_markup(
1357
+ f"[muted]CONTEXT[/muted] {render_meter(ratio)} [dim]{pct}[/dim]\n"
1358
+ f"[muted]VECTOR DB[/muted] {rag_label}\n"
1359
+ f"[muted]SHORTCUTS[/muted] [accent]/new[/accent] · [accent]/model[/accent] · "
1360
+ f"[accent]/account[/accent] · [accent]@file[/accent] · [accent]/exit[/accent]"
1361
+ )
1362
+ grid.add_row(left, right)
1363
+ else:
1364
+ grid.add_column()
1365
+ grid.add_row(
1366
+ Text.from_markup(
1367
+ f"[muted]MODEL[/muted] [model]{engine.active_model}[/model]\n"
1368
+ f"[muted]BUDGET[/muted] {budget.format_summary()}\n"
1369
+ f"[muted]RAG[/muted] {rag_label}\n"
1370
+ f"[muted]CMDS[/muted] /model · @file · /help"
1371
+ )
1372
+ )
1373
+
1374
+ console.print()
1375
+ console.print(
1376
+ Panel(
1377
+ grid,
1378
+ box=box.ROUNDED,
1379
+ title="[heading]◆ VALKYRIE CHAT[/heading]",
1380
+ title_align="left",
1381
+ border_style="bright_cyan",
1382
+ padding=(0, 1),
1383
+ )
1384
+ )
1385
+ console.print()
1386
+
1387
+
1388
+ def _build_toolbar(engine: ChatEngine) -> HTML:
1389
+ """Build live bottom toolbar HTML for prompt_toolkit."""
1390
+ budget = engine.get_budget()
1391
+ if budget.context_window:
1392
+ pct = int((budget.used_tokens / budget.context_window) * 100)
1393
+ ctx_str = f"ctx {pct}%"
1394
+ else:
1395
+ ctx_str = f"ctx ~{budget.used_tokens:,}"
1396
+
1397
+ rag_state = "pinecone:on" if engine.auto_rag else "pinecone:off"
1398
+ return HTML(
1399
+ f" <b>◆ {engine.active_model}</b> │ {ctx_str} │ {rag_state} "
1400
+ f"│ <i>/new /model /web /auto @file /help</i> "
1401
+ )
1402
+
1403
+
1404
+ def run_chat_repl(engine: ChatEngine) -> None:
1405
+ """Run the interactive terminal chat loop."""
1406
+ registry = build_command_registry(engine)
1407
+ completer = ValkyrieCompleter(registry, engine.workspace_root, model_registry=engine.registry)
1408
+ session: PromptSession[str] = PromptSession(
1409
+ completer=completer,
1410
+ complete_while_typing=True,
1411
+ style=_PROMPT_STYLE,
1412
+ bottom_toolbar=lambda: _build_toolbar(engine),
1413
+ )
1414
+
1415
+ _render_chat_hud(engine)
1416
+
1417
+ interrupt_pending = False
1418
+ while True:
1419
+ try:
1420
+ provider, _, model_short = engine.active_model.partition("/")
1421
+ badge = f"{provider}/{model_short}" if model_short else engine.active_model
1422
+ prompt_text = HTML(
1423
+ f"<ansibrightcyan>◆ valkyrie</ansibrightcyan> "
1424
+ f"<ansibrightmagenta>[{badge}]</ansibrightmagenta> "
1425
+ f"<b>›</b> "
1426
+ )
1427
+ user_input = session.prompt(prompt_text)
1428
+ interrupt_pending = False
1429
+ except KeyboardInterrupt:
1430
+ if interrupt_pending:
1431
+ console.print()
1432
+ print_info("Session closed.")
1433
+ break
1434
+ interrupt_pending = True
1435
+ console.print(" [dim](Press Ctrl+C again, Ctrl+D, or /exit to quit.)[/dim]")
1436
+ continue
1437
+ except EOFError:
1438
+ console.print()
1439
+ print_info("Session closed.")
1440
+ break
1441
+
1442
+ stripped = user_input.strip()
1443
+ if not stripped:
1444
+ continue
1445
+
1446
+ if stripped.startswith("/"):
1447
+ if not _handle_slash_command(stripped, engine, registry):
1448
+ break
1449
+ continue
1450
+
1451
+ asyncio.run(engine.send_turn(stripped))
1452
+
1453
+ # Instant 1-key recovery when a model returns 404 / deprecated
1454
+ if engine.last_suggested_model and sys.stdin.isatty():
1455
+ suggested = engine.last_suggested_model
1456
+ engine.last_suggested_model = None
1457
+ if click.confirm(f" ▸ Switch active model to {suggested} now?", default=True):
1458
+ _attempt_model_switch(engine, suggested)