eva-cli 3.0.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 (74) hide show
  1. eva/__init__.py +3 -0
  2. eva/budget.py +31 -0
  3. eva/cache/__init__.py +17 -0
  4. eva/cache/cache.py +40 -0
  5. eva/cache.py +19 -0
  6. eva/chat_session.py +5 -0
  7. eva/cli/__init__.py +3 -0
  8. eva/cli/app.py +851 -0
  9. eva/cli.py +5 -0
  10. eva/config/__init__.py +33 -0
  11. eva/config/config.py +129 -0
  12. eva/config.py +35 -0
  13. eva/context/__init__.py +19 -0
  14. eva/context/finder.py +5 -0
  15. eva/context/gitignore.py +5 -0
  16. eva/context/io.py +5 -0
  17. eva/context/tokenizer.py +5 -0
  18. eva/context/tree.py +5 -0
  19. eva/diagnostics.py +9 -0
  20. eva/git_ops.py +15 -0
  21. eva/indexing/__init__.py +18 -0
  22. eva/indexing/finder.py +42 -0
  23. eva/indexing/io.py +35 -0
  24. eva/indexing/repo_index.py +240 -0
  25. eva/indexing/tokenizer.py +37 -0
  26. eva/indexing/tree.py +60 -0
  27. eva/plugins/__init__.py +3 -0
  28. eva/prompts/__init__.py +36 -0
  29. eva/providers/__init__.py +150 -0
  30. eva/providers/gemini_provider.py +72 -0
  31. eva/providers/groq_provider.py +37 -0
  32. eva/providers/llamacpp_provider.py +69 -0
  33. eva/providers/ollama_provider.py +70 -0
  34. eva/providers/openai_compat.py +57 -0
  35. eva/providers/opencode_zen_provider.py +53 -0
  36. eva/providers/openrouter_provider.py +55 -0
  37. eva/replay/__init__.py +11 -0
  38. eva/replay/player.py +91 -0
  39. eva/replay/recorder.py +67 -0
  40. eva/router/__init__.py +25 -0
  41. eva/router/gemini_provider.py +5 -0
  42. eva/router/groq_provider.py +5 -0
  43. eva/router/openai_compat.py +5 -0
  44. eva/router/opencode_zen_provider.py +5 -0
  45. eva/router/openrouter_provider.py +5 -0
  46. eva/security/__init__.py +32 -0
  47. eva/security/audit.py +126 -0
  48. eva/security/redaction.py +80 -0
  49. eva/security/sandbox.py +55 -0
  50. eva/security/work_safety.py +85 -0
  51. eva/shell/__init__.py +3 -0
  52. eva/shell/runner.py +6 -0
  53. eva/telemetry/__init__.py +10 -0
  54. eva/telemetry/diagnostics.py +43 -0
  55. eva/telemetry/metrics.py +68 -0
  56. eva/ui/formatter.py +46 -0
  57. eva/ui/streaming.py +21 -0
  58. eva/work_safety.py +21 -0
  59. eva/workflows/__init__.py +39 -0
  60. eva/workflows/budget.py +139 -0
  61. eva/workflows/builtins/dependency_audit.yaml +12 -0
  62. eva/workflows/builtins/repo_health.yaml +16 -0
  63. eva/workflows/builtins/security_scan.yaml +12 -0
  64. eva/workflows/chat_session.py +54 -0
  65. eva/workflows/engine.py +267 -0
  66. eva/workspace/__init__.py +39 -0
  67. eva/workspace/git_ops.py +202 -0
  68. eva/workspace/gitignore.py +47 -0
  69. eva/workspace/session.py +184 -0
  70. eva_cli-3.0.0.dist-info/METADATA +344 -0
  71. eva_cli-3.0.0.dist-info/RECORD +74 -0
  72. eva_cli-3.0.0.dist-info/WHEEL +4 -0
  73. eva_cli-3.0.0.dist-info/entry_points.txt +2 -0
  74. eva_cli-3.0.0.dist-info/licenses/LICENSE +21 -0
eva/cli/app.py ADDED
@@ -0,0 +1,851 @@
1
+ import importlib.metadata
2
+ import os
3
+ import subprocess
4
+ import time
5
+ from pathlib import Path
6
+
7
+ import typer
8
+ from rich.console import Console
9
+
10
+ from eva.config import (
11
+ KeyringUnavailableError,
12
+ clear_api_key,
13
+ get_api_key,
14
+ get_api_key_env_var,
15
+ get_config_file,
16
+ keyring_backend_available,
17
+ load_config,
18
+ save_config,
19
+ set_api_key,
20
+ )
21
+ from eva.indexing.finder import find_files
22
+ from eva.indexing.io import ContextReadError, read_text_file_for_context
23
+ from eva.indexing.repo_index import build_dep_graph, detect_stack
24
+ from eva.indexing.tokenizer import trim_context
25
+ from eva.indexing.tree import generate_tree
26
+ from eva.prompts import (
27
+ ANALYZE_SYSTEM_PROMPT,
28
+ ASK_SYSTEM_PROMPT,
29
+ COMMIT_SYSTEM_PROMPT,
30
+ EDIT_SYSTEM_PROMPT,
31
+ EXPLAIN_SYSTEM_PROMPT,
32
+ WORK_SYSTEM_PROMPT,
33
+ )
34
+ from eva.providers import dispatch, get_provider
35
+ from eva.replay import display_replay_session, list_replay_sessions, record_replay_event
36
+ from eva.security import run_sandboxed
37
+ from eva.security.work_safety import (
38
+ CommandExtractionError,
39
+ UnsafeCommandError,
40
+ append_command_audit,
41
+ get_command_audit_log,
42
+ parse_safe_command,
43
+ )
44
+ from eva.telemetry.diagnostics import setup_logging
45
+ from eva.ui.formatter import is_ai_error, print_error, print_info, print_markdown, print_success
46
+ from eva.ui.streaming import stream_response
47
+ from eva.workflows.budget import load_budget, normalize_usage_stats, remaining_budget
48
+ from eva.workflows.chat_session import run_chat_session
49
+ from eva.workflows.engine import list_workflows, load_workflow, run_workflow
50
+ from eva.workspace.git_ops import apply_unified_diff, extract_unified_diff, run_git
51
+ from eva.workspace.session import (
52
+ add_bookmark,
53
+ add_note,
54
+ create_workspace,
55
+ get_active_workspace,
56
+ get_workspace,
57
+ list_workspaces,
58
+ set_active_workspace,
59
+ )
60
+
61
+ app = typer.Typer(
62
+ name="eva",
63
+ help="Eva — Command Line Intelligence",
64
+ add_completion=False,
65
+ )
66
+ config_app = typer.Typer(help="Manage Eva configuration and API keys.")
67
+ budget_app = typer.Typer(help="Inspect rate limits and token budget usage.")
68
+ workflow_app = typer.Typer(help="Run and manage declarative multi-step workflows.")
69
+ workspace_app = typer.Typer(help="Manage named session workspaces, notes, and bookmarks.")
70
+
71
+ app.add_typer(config_app, name="config")
72
+ app.add_typer(budget_app, name="budget")
73
+ app.add_typer(workflow_app, name="workflow")
74
+ app.add_typer(workspace_app, name="workspace")
75
+
76
+ console = Console()
77
+ err_console = Console(stderr=True)
78
+
79
+
80
+ def _get_version() -> str:
81
+ try:
82
+ return importlib.metadata.version("eva-cli")
83
+ except importlib.metadata.PackageNotFoundError:
84
+ from eva import __version__
85
+
86
+ return __version__
87
+
88
+
89
+ def version_callback(value: bool):
90
+ if value:
91
+ print(f"Eva {_get_version()}")
92
+ raise typer.Exit()
93
+
94
+
95
+ @app.callback()
96
+ def main(
97
+ version: bool = typer.Option(
98
+ None,
99
+ "--version",
100
+ "-v",
101
+ help="Show version and exit.",
102
+ callback=version_callback,
103
+ is_eager=True,
104
+ ),
105
+ verbose: bool = typer.Option(
106
+ False,
107
+ "--verbose",
108
+ "-V",
109
+ help="Enable verbose debug logging.",
110
+ ),
111
+ ):
112
+ setup_logging(verbose=verbose)
113
+
114
+
115
+ def _read_context_file(path: Path, header: str = "") -> str:
116
+ try:
117
+ text, warnings = read_text_file_for_context(path)
118
+ for warning in warnings:
119
+ err_console.print(f"[warning]Warning: {warning}[/warning]")
120
+ prefix = f"\n=== {header} ===\n" if header else "\n"
121
+ return f"{prefix}{text}\n"
122
+ except ContextReadError as exc:
123
+ print_error(str(exc))
124
+ raise typer.Exit(1) from exc
125
+
126
+
127
+ @app.command()
128
+ def ask(
129
+ query: list[str] = typer.Argument(..., help="The prompt or question to ask Eva"),
130
+ files: list[Path] = typer.Option(None, "--file", "-f", help="Include file content as context"),
131
+ provider: str | None = typer.Option(None, "--provider", "-p", help="Pin to a specific provider"),
132
+ ):
133
+ """Ask a question, optionally including local file context."""
134
+ config = load_config()
135
+ context = ""
136
+ if files:
137
+ for path in files:
138
+ context += _read_context_file(path, header=f"File: {path}")
139
+
140
+ query_str = " ".join(query)
141
+ stream = dispatch(ASK_SYSTEM_PROMPT, query_str, context, config, pinned_provider=provider)
142
+ result = stream_response(stream)
143
+ if is_ai_error(result):
144
+ print_error(result.strip())
145
+ raise typer.Exit(1)
146
+ print_markdown(result)
147
+
148
+
149
+ @app.command()
150
+ def explain(
151
+ target: str = typer.Argument(None, help="File path, concept, or pipe input to explain"),
152
+ provider: str | None = typer.Option(None, "--provider", "-p", help="Pin to a specific provider"),
153
+ ):
154
+ """Explain a file, error log, or piped stdout."""
155
+ config = load_config()
156
+ context = ""
157
+ query = "Explain this content."
158
+
159
+ # Check for stdin (piped input)
160
+ import sys
161
+
162
+ if not sys.stdin.isatty():
163
+ piped_input = sys.stdin.read()
164
+ if piped_input.strip():
165
+ context = f"\n=== Piped Input ===\n{piped_input}\n"
166
+ if target:
167
+ query = target
168
+
169
+ if not context and target:
170
+ path = Path(target)
171
+ if path.exists() and path.is_file():
172
+ context = _read_context_file(path, header=f"File: {path}")
173
+ query = f"Explain the file {target}."
174
+ elif path.exists() and path.is_dir():
175
+ stack = detect_stack(path)
176
+ dep_graph = build_dep_graph(path)
177
+ context = f"\n=== Project Stack ===\n{stack.to_summary_string()}\n\n=== Dependency Graph ===\n{dep_graph.to_summary_string()}\n"
178
+ query = f"Explain the repository structure and architecture at {target}."
179
+ else:
180
+ query = f"Explain: {target}"
181
+
182
+ if not context and not target:
183
+ path = Path(".")
184
+ stack = detect_stack(path)
185
+ dep_graph = build_dep_graph(path)
186
+ context = f"\n=== Project Stack ===\n{stack.to_summary_string()}\n\n=== Dependency Graph ===\n{dep_graph.to_summary_string()}\n"
187
+ query = "Explain the project structure, stack, and architecture of this repository."
188
+
189
+ stream = dispatch(EXPLAIN_SYSTEM_PROMPT, query, context, config, pinned_provider=provider)
190
+ result = stream_response(stream)
191
+ if is_ai_error(result):
192
+ print_error(result.strip())
193
+ raise typer.Exit(1)
194
+ print_markdown(result)
195
+
196
+
197
+ @app.command()
198
+ def analyze(
199
+ files: list[Path] = typer.Option(None, "--file", "-f", help="Files to analyze"),
200
+ provider: str | None = typer.Option(None, "--provider", "-p", help="Pin to a specific provider"),
201
+ ):
202
+ """Analyze logs, errors, or file output."""
203
+ config = load_config()
204
+ context = ""
205
+ import sys
206
+
207
+ if not sys.stdin.isatty():
208
+ piped_input = sys.stdin.read()
209
+ if piped_input.strip():
210
+ context += f"\n=== Piped Input ===\n{piped_input}\n"
211
+
212
+ if files:
213
+ for path in files:
214
+ context += _read_context_file(path, header=f"File: {path}")
215
+
216
+ if not context.strip():
217
+ print_error("Provide files with -f or pipe stdout into 'eva analyze'.")
218
+ raise typer.Exit(1)
219
+
220
+ query = "Analyze the provided content, identify issues, and suggest solutions."
221
+ stream = dispatch(ANALYZE_SYSTEM_PROMPT, query, context, config, pinned_provider=provider)
222
+ result = stream_response(stream)
223
+ if is_ai_error(result):
224
+ print_error(result.strip())
225
+ raise typer.Exit(1)
226
+ print_markdown(result)
227
+
228
+
229
+ @app.command()
230
+ def chat(
231
+ provider: str | None = typer.Option(None, "--provider", "-p", help="Pin to a specific provider"),
232
+ session: str | None = typer.Option(None, "--session", "-s", help="Save chat transcript under this session name"),
233
+ resume: bool = typer.Option(False, "--resume", help="Resume the named session"),
234
+ ):
235
+ """Interactive REPL."""
236
+ config = load_config()
237
+ run_chat_session(config=config, provider=provider, session=session, resume=resume)
238
+
239
+
240
+ @app.command()
241
+ def work(
242
+ query: list[str] = typer.Argument(..., help="The natural language command description"),
243
+ provider: str | None = typer.Option(None, "--provider", "-p", help="Pin to a specific provider"),
244
+ auto_confirm: bool = typer.Option(False, "--yes", "-y", help="Auto-confirm execution"),
245
+ dry_run: bool = typer.Option(False, "--dry-run", help="Generate and audit the command without executing it"),
246
+ ):
247
+ """Execute a command generated from natural language."""
248
+ config = load_config()
249
+ query_str = " ".join(query)
250
+
251
+ from rich.live import Live
252
+ from rich.spinner import Spinner
253
+
254
+ stream = dispatch(WORK_SYSTEM_PROMPT, query_str, "", config, pinned_provider=provider)
255
+
256
+ model_output = ""
257
+ spinner = Spinner("dots", text="Generating command...")
258
+ with Live(spinner, console=err_console, refresh_per_second=15, transient=True):
259
+ for chunk in stream:
260
+ model_output += chunk
261
+
262
+ if is_ai_error(model_output):
263
+ append_command_audit(
264
+ {"query": query_str, "model_output": model_output, "executed": False, "blocked_reason": "provider_error"}
265
+ )
266
+ print_error(model_output.strip())
267
+ raise typer.Exit(1)
268
+
269
+ try:
270
+ parsed = parse_safe_command(model_output)
271
+ except UnsafeCommandError as exc:
272
+ append_command_audit(
273
+ {
274
+ "query": query_str,
275
+ "model_output": model_output,
276
+ "executed": False,
277
+ "blocked_reason": f"unsafe_command: {exc}",
278
+ }
279
+ )
280
+ print_error(f"Refusing to execute unsafe command: {exc}")
281
+ raise typer.Exit(1) from exc
282
+ except CommandExtractionError as exc:
283
+ append_command_audit(
284
+ {"query": query_str, "model_output": model_output, "executed": False, "blocked_reason": str(exc)}
285
+ )
286
+ print_error(f"Refusing to execute ambiguous model output: {exc}")
287
+ raise typer.Exit(1) from exc
288
+
289
+ err_console.print(f"[info]ℹ Generated command:\n> {parsed.command}\n[/info]")
290
+
291
+ if dry_run:
292
+ append_command_audit(
293
+ {"query": query_str, "command": parsed.command, "argv": parsed.argv, "executed": False, "dry_run": True}
294
+ )
295
+ print_info(f"Dry run only. Audit log: {get_command_audit_log()}")
296
+ return
297
+
298
+ execute = auto_confirm
299
+ if not execute:
300
+ execute = typer.confirm("Do you want to execute this command?")
301
+
302
+ if execute:
303
+ start_t = time.time()
304
+ active_session = get_active_workspace()
305
+
306
+ if config.general.sandbox_risky_commands:
307
+ print_info("[Eva Sandbox] Executing command in restricted sandbox environment...")
308
+ res = run_sandboxed(parsed.command, cwd=Path.cwd())
309
+ returncode = getattr(res, "returncode", 0)
310
+ stdout_str = res.stdout if isinstance(getattr(res, "stdout", None), str) else ""
311
+ stderr_str = res.stderr if isinstance(getattr(res, "stderr", None), str) else ""
312
+ if stdout_str:
313
+ console.print(stdout_str, end="")
314
+ if stderr_str:
315
+ err_console.print(stderr_str, end="")
316
+ output_str = stdout_str + ("\n" + stderr_str if stderr_str else "")
317
+ else:
318
+ res = subprocess.run(parsed.command, shell=True, check=False, capture_output=True, text=True)
319
+ returncode = getattr(res, "returncode", 0)
320
+ stdout_str = res.stdout if isinstance(getattr(res, "stdout", None), str) else ""
321
+ stderr_str = res.stderr if isinstance(getattr(res, "stderr", None), str) else ""
322
+ if stdout_str:
323
+ console.print(stdout_str, end="")
324
+ if stderr_str:
325
+ err_console.print(stderr_str, end="")
326
+ output_str = stdout_str + ("\n" + stderr_str if stderr_str else "")
327
+
328
+ duration = time.time() - start_t
329
+
330
+ record_replay_event(
331
+ session_id=active_session,
332
+ command=parsed.command,
333
+ output=output_str,
334
+ exit_code=returncode,
335
+ duration_s=duration,
336
+ cwd=Path.cwd(),
337
+ )
338
+
339
+ append_command_audit(
340
+ {
341
+ "query": query_str,
342
+ "command": parsed.command,
343
+ "argv": parsed.argv,
344
+ "executed": True,
345
+ "return_code": returncode,
346
+ }
347
+ )
348
+ if returncode != 0:
349
+ # Check if execution failed due to missing root/sudo privileges
350
+ if not parsed.command.strip().startswith("sudo ") and typer.confirm(
351
+ "Command failed due to missing privileges. Retry with sudo?", default=True
352
+ ):
353
+ sudo_cmd = f"sudo {parsed.command}"
354
+ s_res = subprocess.run(sudo_cmd, shell=True, check=False)
355
+ if s_res.returncode != 0:
356
+ raise typer.Exit(s_res.returncode)
357
+ return
358
+ raise typer.Exit(returncode)
359
+ else:
360
+ append_command_audit(
361
+ {
362
+ "query": query_str,
363
+ "command": parsed.command,
364
+ "argv": parsed.argv,
365
+ "executed": False,
366
+ "blocked_reason": "user_declined",
367
+ }
368
+ )
369
+
370
+
371
+ @app.command()
372
+ def tree(
373
+ path: Path = typer.Argument(Path("."), help="Directory path to visualize"),
374
+ ):
375
+ """Generate a directory tree respecting .gitignore."""
376
+ result = generate_tree(path)
377
+ console.print(result, end="")
378
+
379
+
380
+ @app.command()
381
+ def find(
382
+ pattern: str = typer.Argument(..., help="File name or glob pattern (e.g. *.py)"),
383
+ path: Path = typer.Argument(Path("."), help="Root directory to search"),
384
+ ):
385
+ """Find files locally respecting .gitignore."""
386
+ found = False
387
+ for p in find_files(path, pattern):
388
+ try:
389
+ rel = p.relative_to(Path.cwd())
390
+ console.print(str(rel))
391
+ except ValueError:
392
+ console.print(str(p))
393
+ found = True
394
+ if not found:
395
+ raise typer.Exit(1)
396
+
397
+
398
+ @app.command()
399
+ def commit(
400
+ provider: str | None = typer.Option(None, "--provider", "-p", help="Pin to a specific provider"),
401
+ ):
402
+ """Generate a conventional commit message for staged changes."""
403
+ diff_res = run_git(["diff", "--staged"])
404
+ if diff_res.returncode != 0:
405
+ print_error("Failed to run git diff.")
406
+ raise typer.Exit(1)
407
+
408
+ diff_text = diff_res.stdout.strip()
409
+ if not diff_text:
410
+ print_error("No staged changes found. Use 'git add' first.")
411
+ raise typer.Exit(1)
412
+
413
+ trimmed_diff = trim_context(diff_text, max_tokens=4000)
414
+ config = load_config()
415
+ stream = dispatch(COMMIT_SYSTEM_PROMPT, "Generate commit message", trimmed_diff, config, pinned_provider=provider)
416
+ result = stream_response(stream)
417
+ if is_ai_error(result):
418
+ print_error(result.strip())
419
+ raise typer.Exit(1)
420
+ print(result.strip())
421
+
422
+
423
+ @app.command()
424
+ def edit(
425
+ query: list[str] = typer.Argument(..., help="Requested code change"),
426
+ files: list[Path] = typer.Option(..., "--file", "-f", help="File to include and allow in the generated diff"),
427
+ provider: str | None = typer.Option(None, "--provider", "-p", help="Pin to a specific provider"),
428
+ apply_changes: bool = typer.Option(False, "--apply", help="Apply the generated patch after review confirmation"),
429
+ ):
430
+ """Generate a reviewable unified diff for file edits."""
431
+ config = load_config()
432
+ context = ""
433
+ for path in files:
434
+ context += _read_context_file(path, header=f"File: {path}")
435
+
436
+ query_str = " ".join(query)
437
+ stream = dispatch(EDIT_SYSTEM_PROMPT, query_str, context, config, pinned_provider=provider)
438
+ result = stream_response(stream)
439
+ if is_ai_error(result):
440
+ print_error(result.strip())
441
+ raise typer.Exit(1)
442
+
443
+ try:
444
+ diff_text = extract_unified_diff(result)
445
+ except ValueError as exc:
446
+ print_error(f"Refusing to apply non-diff model output: {exc}")
447
+ console.print(result)
448
+ raise typer.Exit(1) from exc
449
+
450
+ console.print(diff_text)
451
+ if not apply_changes and not typer.confirm("Apply this patch?"):
452
+ print_info("Patch not applied.")
453
+ return
454
+
455
+ apply_unified_diff(diff_text)
456
+ print_success("Patch applied.")
457
+
458
+
459
+ @app.command()
460
+ def replay(
461
+ session: str = typer.Argument(None, help="Session name or ID to replay"),
462
+ list_sessions: bool = typer.Option(False, "--list", "-l", help="List all available replay sessions"),
463
+ ):
464
+ """Replay recorded terminal execution sessions."""
465
+ if list_sessions or not session:
466
+ sessions = list_replay_sessions()
467
+ if not sessions:
468
+ print_info("No recorded replay sessions found.")
469
+ return
470
+
471
+ from rich.table import Table
472
+
473
+ table = Table(title="Recorded Replay Sessions")
474
+ table.add_column("Session ID", style="cyan")
475
+ table.add_column("Created At", style="yellow")
476
+ table.add_column("Recorded Events", style="magenta")
477
+
478
+ for s in sessions:
479
+ table.add_row(s["session_id"], s["created_at"], str(s["event_count"]))
480
+
481
+ console.print(table)
482
+ return
483
+
484
+ try:
485
+ display_replay_session(session, console=console)
486
+ except FileNotFoundError as exc:
487
+ print_error(str(exc))
488
+ raise typer.Exit(1) from exc
489
+
490
+
491
+ @app.command()
492
+ def use(provider: str):
493
+ """Set the default AI provider."""
494
+ config = load_config()
495
+ if provider not in config.providers:
496
+ print_error(f"Provider '{provider}' not found. Available providers: {', '.join(config.providers.keys())}")
497
+ raise typer.Exit(1)
498
+ config.general.default_provider = provider
499
+ save_config(config)
500
+ print_success(f"Default provider set to {provider}")
501
+
502
+
503
+ @app.command()
504
+ def usage():
505
+ """Show normalized local provider usage counters."""
506
+ show_budget()
507
+
508
+
509
+ @config_app.command("set-provider")
510
+ def set_provider(name: str):
511
+ """Change the persistent default provider."""
512
+ use(name)
513
+
514
+
515
+ @config_app.command("set-model")
516
+ def set_model_cmd(
517
+ provider: str = typer.Argument(..., help="The provider name (e.g. openrouter, groq, gemini, ollama, llamacpp)"),
518
+ model: str = typer.Argument(..., help="The model identifier to use for this provider"),
519
+ ):
520
+ """Set the active model for a specific provider."""
521
+ config = load_config()
522
+ if provider not in config.providers:
523
+ print_error(f"Provider '{provider}' not found. Available providers: {', '.join(config.providers.keys())}")
524
+ raise typer.Exit(1)
525
+
526
+ config.providers[provider].model = model
527
+ save_config(config)
528
+ print_success(f"Model for provider '{provider}' set to '{model}'.")
529
+
530
+
531
+ @config_app.command("set-key")
532
+ def set_key_cmd(
533
+ provider: str = typer.Argument(..., help="The name of the provider (e.g. groq, openrouter)"),
534
+ key: str | None = typer.Argument(None, help="The API key (if omitted, you will be prompted securely)"),
535
+ ):
536
+ """Store an API key via keyring."""
537
+ config = load_config()
538
+ if provider not in config.providers:
539
+ print_error(f"Provider '{provider}' not found. Available providers: {', '.join(config.providers.keys())}")
540
+ raise typer.Exit(1)
541
+
542
+ if not key:
543
+ import getpass
544
+
545
+ key = getpass.getpass(f"Enter API key for {provider}: ")
546
+ if not key.strip():
547
+ print_error("API key cannot be empty.")
548
+ return
549
+
550
+ try:
551
+ set_api_key(provider, key.strip())
552
+ except KeyringUnavailableError as exc:
553
+ print_error(str(exc))
554
+ env_var = get_api_key_env_var(provider)
555
+ print_info(f"You can also export {env_var} in your shell environment.")
556
+ raise typer.Exit(1) from exc
557
+
558
+ print_success(f"API key for '{provider}' saved successfully.")
559
+
560
+
561
+ @config_app.command("remove-key")
562
+ def remove_key_cmd(
563
+ provider: str = typer.Argument(..., help="The name of the provider (e.g. groq, openrouter, gemini)"),
564
+ ):
565
+ """Remove a stored API key from the OS keyring."""
566
+ config = load_config()
567
+ if provider not in config.providers:
568
+ print_error(f"Provider '{provider}' not found. Available providers: {', '.join(config.providers.keys())}")
569
+ raise typer.Exit(1)
570
+
571
+ try:
572
+ clear_api_key(provider)
573
+ except KeyringUnavailableError as exc:
574
+ print_error(str(exc))
575
+ raise typer.Exit(1) from exc
576
+
577
+ print_success(f"API key for '{provider}' removed successfully.")
578
+
579
+
580
+ @config_app.command("show")
581
+ def show_config():
582
+ """Display current configuration, default provider, and key statuses."""
583
+ config = load_config()
584
+
585
+ from rich.table import Table
586
+
587
+ table = Table(title="Eva Configuration")
588
+ table.add_column("Property", style="cyan")
589
+ table.add_column("Value", style="magenta")
590
+
591
+ table.add_row("Config Path", str(get_config_file()))
592
+ table.add_row("Default Provider", config.general.default_provider)
593
+ table.add_row("Fallback Enabled", str(config.general.fallback_enabled))
594
+ table.add_row("Fallback Order", ", ".join(config.general.fallback_order))
595
+
596
+ console.print(table)
597
+ console.print()
598
+
599
+ prov_table = Table(title="Configured Providers & Key Status")
600
+ prov_table.add_column("Provider", style="cyan")
601
+ prov_table.add_column("Model", style="yellow")
602
+ prov_table.add_column("API Key Status", style="green")
603
+
604
+ for name, p_cfg in config.providers.items():
605
+ key = get_api_key(name)
606
+ status = "[green]Configured[/green]" if key else "[red]Missing[/red]"
607
+ is_default = " (default)" if name == config.general.default_provider else ""
608
+ prov_table.add_row(f"{name}{is_default}", p_cfg.model, status)
609
+
610
+ console.print(prov_table)
611
+
612
+
613
+ @config_app.command("doctor")
614
+ def doctor():
615
+ """Diagnose environment, keyring backend, and provider connectivity."""
616
+ print_info("Running Eva Environment Doctor...\n")
617
+
618
+ ok, info = keyring_backend_available()
619
+ if ok:
620
+ print_success(f"Keyring Backend: Available ({info})")
621
+ else:
622
+ print_error(f"Keyring Backend: Unavailable ({info})")
623
+
624
+ config = load_config()
625
+ print_info(f"Default Provider: {config.general.default_provider}")
626
+
627
+ for name in config.providers:
628
+ key = get_api_key(name)
629
+ env_var = get_api_key_env_var(name)
630
+ if key:
631
+ source = f"env var {env_var}" if os.getenv(env_var) else "keyring"
632
+ print_success(f"Provider '{name}': API key found ({source})")
633
+ else:
634
+ print_error(f"Provider '{name}': No API key set (keyring or {env_var})")
635
+
636
+
637
+ @budget_app.command("show")
638
+ def show_budget():
639
+ """Show current request usage counts and rate limit budgets."""
640
+ config = load_config()
641
+ budget = load_budget()
642
+
643
+ from rich.table import Table
644
+
645
+ table = Table(title="Token Budget & Rate Limit Usage")
646
+ table.add_column("Provider", style="cyan")
647
+ table.add_column("RPM Limit", style="yellow")
648
+ table.add_column("Used (Min)", style="magenta")
649
+ table.add_column("RPD Limit", style="yellow")
650
+ table.add_column("Used (Day)", style="magenta")
651
+
652
+ for name in config.providers:
653
+ provider = get_provider(name)
654
+ if not provider:
655
+ continue
656
+
657
+ rpd_rem, rpm_rem = remaining_budget(name, provider.max_rpm, provider.max_rpd)
658
+ stats = budget.usage_by_provider.get(name)
659
+ stats_norm = normalize_usage_stats(stats) if stats else None
660
+
661
+ used_min = stats_norm.requests_this_minute if stats_norm else 0
662
+ used_day = stats_norm.requests_today if stats_norm else 0
663
+
664
+ table.add_row(
665
+ name,
666
+ str(provider.max_rpm),
667
+ f"{used_min} ({rpm_rem} left)",
668
+ str(provider.max_rpd),
669
+ f"{used_day} ({rpd_rem} left)",
670
+ )
671
+
672
+ console.print(table)
673
+
674
+
675
+ # Workflow commands
676
+ @workflow_app.command("run")
677
+ def workflow_run_cmd(
678
+ name: str = typer.Argument(..., help="Workflow name or YAML file path"),
679
+ provider: str | None = typer.Option(None, "--provider", "-p", help="Pin to a specific provider"),
680
+ ):
681
+ """Walk through workflow steps with an approval gate between each step."""
682
+ config = load_config()
683
+ try:
684
+ wf = load_workflow(name)
685
+ except (FileNotFoundError, ValueError) as exc:
686
+ print_error(str(exc))
687
+ raise typer.Exit(1) from exc
688
+
689
+ results = run_workflow(wf, config=config, interactive=True)
690
+ failed = [r for r in results if r.get("status") in {"failed", "blocked_unsafe", "blocked_ambiguous"}]
691
+ if failed:
692
+ raise typer.Exit(1)
693
+
694
+
695
+ @workflow_app.command("list")
696
+ def workflow_list_cmd():
697
+ """List all available built-in and user-defined workflows."""
698
+ from rich.table import Table
699
+
700
+ wfs = list_workflows()
701
+ if not wfs:
702
+ print_info("No workflows found.")
703
+ return
704
+
705
+ table = Table(title="Available Workflows")
706
+ table.add_column("Name", style="cyan")
707
+ table.add_column("Source", style="yellow")
708
+ table.add_column("Description", style="magenta")
709
+
710
+ for w in wfs:
711
+ table.add_row(w["name"], w["source"], w["description"])
712
+
713
+ console.print(table)
714
+
715
+
716
+ @workflow_app.command("show")
717
+ def workflow_show_cmd(
718
+ name: str = typer.Argument(..., help="Workflow name or YAML file path"),
719
+ ):
720
+ """Display workflow definition and steps without running it."""
721
+ from rich.table import Table
722
+
723
+ try:
724
+ wf = load_workflow(name)
725
+ except (FileNotFoundError, ValueError) as exc:
726
+ print_error(str(exc))
727
+ raise typer.Exit(1) from exc
728
+
729
+ console.print(f"[bold cyan]Workflow:[/bold cyan] {wf.name} (v{wf.version})")
730
+ if wf.description:
731
+ console.print(f"[italic]{wf.description}[/italic]\n")
732
+
733
+ table = Table(title=f"Steps in {wf.name}")
734
+ table.add_column("#", style="yellow")
735
+ table.add_column("Step Name", style="cyan")
736
+ table.add_column("Command", style="green")
737
+ table.add_column("Description", style="magenta")
738
+
739
+ for i, s in enumerate(wf.steps, start=1):
740
+ table.add_row(str(i), s.name, s.command, s.description)
741
+
742
+ console.print(table)
743
+
744
+
745
+ # Workspace commands
746
+ @workspace_app.callback(invoke_without_command=True)
747
+ def workspace_callback(
748
+ ctx: typer.Context,
749
+ ):
750
+ """Manage session workspaces, scoped history, notes, and bookmarks."""
751
+ if ctx.invoked_subcommand is None:
752
+ active = get_active_workspace()
753
+ ws = get_workspace(active)
754
+ _display_workspace_summary(ws)
755
+
756
+
757
+ def _display_workspace_summary(ws):
758
+ console.print(f"[bold cyan]Workspace Session:[/bold cyan] {ws.name}")
759
+ console.print(f"[dim]Created: {ws.created_at}[/dim]\n")
760
+
761
+ if ws.notes:
762
+ console.print("[bold yellow]Notes:[/bold yellow]")
763
+ for note in ws.notes:
764
+ console.print(f" • {note}")
765
+ console.print()
766
+
767
+ if ws.bookmarks:
768
+ console.print("[bold green]Bookmarks:[/bold green]")
769
+ for bm in ws.bookmarks:
770
+ console.print(f" 🔖 {bm}")
771
+ console.print()
772
+
773
+ if ws.history:
774
+ console.print(f"[bold magenta]Recent Activity ({len(ws.history)} items):[/bold magenta]")
775
+ for h in ws.history[-5:]:
776
+ ts = h.get("timestamp", "")[:19].replace("T", " ")
777
+ console.print(f" [{ts}] ({h.get('type')}) {h.get('content')}")
778
+ console.print()
779
+
780
+
781
+ @workspace_app.command("switch")
782
+ def workspace_switch_cmd(name: str = typer.Argument(..., help="Workspace name to switch to")):
783
+ """Switch active workspace."""
784
+ set_active_workspace(name)
785
+ print_success(f"Switched active workspace to '{name}'.")
786
+
787
+
788
+ @workspace_app.command("create")
789
+ def workspace_create_cmd(name: str = typer.Argument(..., help="Workspace name to create")):
790
+ """Create a new workspace."""
791
+ ws = create_workspace(name)
792
+ set_active_workspace(name)
793
+ print_success(f"Created and activated workspace '{ws.name}'.")
794
+
795
+
796
+ @workspace_app.command("list")
797
+ def workspace_list_cmd():
798
+ """List all workspace sessions."""
799
+ active = get_active_workspace()
800
+ all_ws = list_workspaces()
801
+
802
+ from rich.table import Table
803
+
804
+ table = Table(title="Workspace Sessions")
805
+ table.add_column("Workspace Name", style="cyan")
806
+ table.add_column("Status", style="yellow")
807
+
808
+ for w in all_ws:
809
+ status = "[green]Active[/green]" if w == active else ""
810
+ table.add_row(w, status)
811
+
812
+ console.print(table)
813
+
814
+
815
+ @workspace_app.command("note")
816
+ def workspace_note_cmd(
817
+ text: list[str] = typer.Argument(..., help="Note text to save in current workspace"),
818
+ ):
819
+ """Add a note to the active workspace."""
820
+ active = get_active_workspace()
821
+ note_str = " ".join(text)
822
+ add_note(active, note_str)
823
+ print_success(f"Added note to workspace '{active}'.")
824
+
825
+
826
+ @workspace_app.command("bookmark")
827
+ def workspace_bookmark_cmd(
828
+ path: str = typer.Argument(..., help="File path or URL to bookmark in current workspace"),
829
+ ):
830
+ """Bookmark a file path or URL in the active workspace."""
831
+ active = get_active_workspace()
832
+ add_bookmark(active, path)
833
+ print_success(f"Bookmarked '{path}' in workspace '{active}'.")
834
+
835
+
836
+ @workspace_app.command("show")
837
+ def workspace_show_cmd(
838
+ name: str | None = typer.Argument(None, help="Workspace name to show (defaults to active)"),
839
+ ):
840
+ """Show details for a workspace."""
841
+ target = name or get_active_workspace()
842
+ ws = get_workspace(target)
843
+ _display_workspace_summary(ws)
844
+
845
+
846
+ def main_entry():
847
+ app()
848
+
849
+
850
+ if __name__ == "__main__":
851
+ main_entry()