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
@@ -0,0 +1,267 @@
1
+ import logging
2
+ import subprocess
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import yaml
8
+ from rich.console import Console
9
+ from rich.prompt import Confirm
10
+
11
+ from eva.config import AppConfig, get_config_dir
12
+ from eva.security.work_safety import (
13
+ CommandExtractionError,
14
+ UnsafeCommandError,
15
+ append_command_audit,
16
+ parse_safe_command,
17
+ )
18
+
19
+ logger = logging.getLogger(__name__)
20
+ err_console = Console(stderr=True)
21
+
22
+
23
+ @dataclass
24
+ class WorkflowStep:
25
+ name: str
26
+ command: str
27
+ description: str = ""
28
+ risk_level: str = "low"
29
+
30
+
31
+ @dataclass
32
+ class Workflow:
33
+ name: str
34
+ description: str
35
+ steps: list[WorkflowStep] = field(default_factory=list)
36
+ version: str = "1.0"
37
+
38
+
39
+ def get_builtins_dir() -> Path:
40
+ return Path(__file__).parent / "builtins"
41
+
42
+
43
+ def get_user_workflows_dir() -> Path:
44
+ d = get_config_dir() / "workflows"
45
+ d.mkdir(parents=True, exist_ok=True)
46
+ return d
47
+
48
+
49
+ def load_workflow(name_or_path: str) -> Workflow:
50
+ """Load a workflow by name or file path."""
51
+ path = Path(name_or_path)
52
+
53
+ if not path.is_file():
54
+ # Try user config dir
55
+ user_path = get_user_workflows_dir() / f"{name_or_path}.yaml"
56
+ if not user_path.is_file():
57
+ user_path = get_user_workflows_dir() / f"{name_or_path}.yml"
58
+
59
+ if user_path.is_file():
60
+ path = user_path
61
+ else:
62
+ # Try builtin workflows
63
+ builtin_path = get_builtins_dir() / f"{name_or_path}.yaml"
64
+ if not builtin_path.is_file():
65
+ builtin_path = get_builtins_dir() / f"{name_or_path}.yml"
66
+
67
+ if builtin_path.is_file():
68
+ path = builtin_path
69
+ else:
70
+ raise FileNotFoundError(f"Workflow '{name_or_path}' not found.")
71
+
72
+ with open(path, "r", encoding="utf-8") as f:
73
+ data = yaml.safe_load(f)
74
+
75
+ if not isinstance(data, dict):
76
+ raise ValueError(f"Invalid workflow format in {path}: expected dictionary root.") # noqa: TRY004
77
+
78
+ name = data.get("name", path.stem)
79
+ description = data.get("description", "")
80
+ version = str(data.get("version", "1.0"))
81
+ steps_raw = data.get("steps", [])
82
+
83
+ if not isinstance(steps_raw, list) or not steps_raw:
84
+ raise ValueError(f"Workflow '{name}' contains no steps.")
85
+
86
+ steps = []
87
+ for i, s in enumerate(steps_raw):
88
+ if not isinstance(s, dict):
89
+ raise ValueError(f"Step {i + 1} in workflow '{name}' is not a dictionary.") # noqa: TRY004
90
+ step_name = s.get("name", f"Step {i + 1}")
91
+ cmd = s.get("command", "")
92
+ if not cmd:
93
+ raise ValueError(f"Step '{step_name}' in workflow '{name}' missing 'command'.")
94
+ desc = s.get("description", "")
95
+ risk = s.get("risk_level", "low")
96
+ steps.append(WorkflowStep(name=step_name, command=cmd, description=desc, risk_level=risk))
97
+
98
+ return Workflow(name=name, description=description, steps=steps, version=version)
99
+
100
+
101
+ def list_workflows() -> list[dict[str, Any]]:
102
+ """List all available workflows (built-in and user-defined)."""
103
+ results: list[dict[str, Any]] = []
104
+ seen: set[str] = set()
105
+
106
+ # Search user directory
107
+ user_dir = get_user_workflows_dir()
108
+ if user_dir.exists():
109
+ for p in sorted(user_dir.glob("*.y*ml")):
110
+ try:
111
+ wf = load_workflow(str(p))
112
+ results.append({"name": wf.name, "description": wf.description, "source": "user", "path": str(p)})
113
+ seen.add(wf.name)
114
+ except (OSError, ValueError, TypeError, yaml.YAMLError) as exc:
115
+ logger.warning("Failed to load user workflow %s: %s", p, exc)
116
+
117
+ # Search built-in directory
118
+ builtin_dir = get_builtins_dir()
119
+ if builtin_dir.exists():
120
+ for p in sorted(builtin_dir.glob("*.y*ml")):
121
+ try:
122
+ wf = load_workflow(str(p))
123
+ if wf.name not in seen:
124
+ results.append(
125
+ {"name": wf.name, "description": wf.description, "source": "builtin", "path": str(p)}
126
+ )
127
+ seen.add(wf.name)
128
+ except (OSError, ValueError, TypeError, yaml.YAMLError) as exc:
129
+ logger.warning("Failed to load builtin workflow %s: %s", p, exc)
130
+
131
+ return results
132
+
133
+
134
+ def run_workflow(
135
+ workflow: Workflow,
136
+ config: AppConfig | None = None,
137
+ interactive: bool = True,
138
+ confirm_func: Any = None,
139
+ ) -> list[dict[str, Any]]:
140
+ """Walk through workflow steps with an approval gate between each step.
141
+
142
+ Reuses the Phase 1 risk and approval safety policy.
143
+ """
144
+ results = []
145
+
146
+ err_console.print(f"[bold cyan]Starting Workflow:[/bold cyan] {workflow.name}")
147
+ if workflow.description:
148
+ err_console.print(f"[dim]{workflow.description}[/dim]")
149
+ err_console.print()
150
+
151
+ for idx, step in enumerate(workflow.steps, start=1):
152
+ err_console.print(f"[bold yellow]Step {idx}/{len(workflow.steps)}:[/bold yellow] {step.name}")
153
+ if step.description:
154
+ err_console.print(f" [italic]{step.description}[/italic]")
155
+ err_console.print(f" [cyan]> {step.command}[/cyan]")
156
+
157
+ # 1. Safety Audit & Parsing using Phase 1 work_safety
158
+ try:
159
+ parsed = parse_safe_command(step.command)
160
+ except UnsafeCommandError as exc:
161
+ append_command_audit(
162
+ {
163
+ "workflow": workflow.name,
164
+ "step": step.name,
165
+ "command": step.command,
166
+ "executed": False,
167
+ "blocked_reason": f"unsafe_command: {exc}",
168
+ }
169
+ )
170
+ err_console.print(f" [bold red]Refusing to execute unsafe command in step '{step.name}': {exc}[/bold red]")
171
+ results.append(
172
+ {
173
+ "step": step.name,
174
+ "command": step.command,
175
+ "executed": False,
176
+ "status": "blocked_unsafe",
177
+ "error": str(exc),
178
+ }
179
+ )
180
+ break
181
+ except CommandExtractionError as exc:
182
+ append_command_audit(
183
+ {
184
+ "workflow": workflow.name,
185
+ "step": step.name,
186
+ "command": step.command,
187
+ "executed": False,
188
+ "blocked_reason": f"ambiguous_command: {exc}",
189
+ }
190
+ )
191
+ err_console.print(f" [bold red]Ambiguous command output in step '{step.name}': {exc}[/bold red]")
192
+ results.append(
193
+ {
194
+ "step": step.name,
195
+ "command": step.command,
196
+ "executed": False,
197
+ "status": "blocked_ambiguous",
198
+ "error": str(exc),
199
+ }
200
+ )
201
+ break
202
+
203
+ # 2. Approval Gate (Human approval before execution)
204
+ if interactive:
205
+ if confirm_func:
206
+ approved = confirm_func(f"Execute step '{step.name}' ({parsed.command})?")
207
+ else:
208
+ approved = Confirm.ask(f"Execute step '{step.name}'?", default=True)
209
+
210
+ if not approved:
211
+ append_command_audit(
212
+ {
213
+ "workflow": workflow.name,
214
+ "step": step.name,
215
+ "command": parsed.command,
216
+ "executed": False,
217
+ "blocked_reason": "user_declined",
218
+ }
219
+ )
220
+ err_console.print(f" [yellow]Step '{step.name}' declined by user. Stopping workflow.[/yellow]")
221
+ results.append(
222
+ {
223
+ "step": step.name,
224
+ "command": parsed.command,
225
+ "executed": False,
226
+ "status": "declined",
227
+ }
228
+ )
229
+ break
230
+
231
+ # 3. Execution
232
+ res = subprocess.run(parsed.command, shell=True, capture_output=True, text=True, check=False)
233
+ append_command_audit(
234
+ {
235
+ "workflow": workflow.name,
236
+ "step": step.name,
237
+ "command": parsed.command,
238
+ "executed": True,
239
+ "return_code": res.returncode,
240
+ }
241
+ )
242
+
243
+ step_result = {
244
+ "step": step.name,
245
+ "command": parsed.command,
246
+ "executed": True,
247
+ "returncode": res.returncode,
248
+ "stdout": res.stdout,
249
+ "stderr": res.stderr,
250
+ "status": "success" if res.returncode == 0 else "failed",
251
+ }
252
+ results.append(step_result)
253
+
254
+ if res.stdout:
255
+ print(res.stdout, end="" if res.stdout.endswith("\n") else "\n")
256
+ if res.stderr and res.returncode != 0:
257
+ err_console.print(f"[red]{res.stderr}[/red]")
258
+
259
+ if res.returncode != 0:
260
+ err_console.print(
261
+ f" [bold red]Step '{step.name}' failed with returncode {res.returncode}. Stopping workflow.[/bold red]"
262
+ )
263
+ break
264
+
265
+ err_console.print(f" [green]✔ Step '{step.name}' complete.[/green]\n")
266
+
267
+ return results
@@ -0,0 +1,39 @@
1
+ from eva.workspace.git_ops import (
2
+ apply_diff_python_fallback,
3
+ apply_unified_diff,
4
+ extract_unified_diff,
5
+ run_git,
6
+ )
7
+ from eva.workspace.gitignore import ALWAYS_IGNORED_DIRS, get_gitignore_spec, is_ignored
8
+ from eva.workspace.session import (
9
+ WorkspaceSession,
10
+ add_bookmark,
11
+ add_history,
12
+ add_note,
13
+ create_workspace,
14
+ get_active_workspace,
15
+ get_workspace,
16
+ list_workspaces,
17
+ redact_secrets,
18
+ set_active_workspace,
19
+ )
20
+
21
+ __all__ = [
22
+ "ALWAYS_IGNORED_DIRS",
23
+ "WorkspaceSession",
24
+ "add_bookmark",
25
+ "add_history",
26
+ "add_note",
27
+ "apply_diff_python_fallback",
28
+ "apply_unified_diff",
29
+ "create_workspace",
30
+ "extract_unified_diff",
31
+ "get_active_workspace",
32
+ "get_gitignore_spec",
33
+ "get_workspace",
34
+ "is_ignored",
35
+ "list_workspaces",
36
+ "redact_secrets",
37
+ "run_git",
38
+ "set_active_workspace",
39
+ ]
@@ -0,0 +1,202 @@
1
+ import os
2
+ import re
3
+ import subprocess
4
+ import tempfile
5
+
6
+ import typer
7
+
8
+ from eva.ui.formatter import print_error
9
+
10
+
11
+ def _fix_diff_headers(diff_text: str) -> str:
12
+ """Fixes malformed hunk headers (e.g., bare '@@') generated by LLMs."""
13
+ lines = diff_text.strip().splitlines()
14
+ fixed_lines = []
15
+ current_file = None
16
+ target_content = []
17
+
18
+ i = 0
19
+ while i < len(lines):
20
+ line = lines[i]
21
+ if line.startswith(("--- ", "+++ ")):
22
+ current_file = line[4:].strip()
23
+ if current_file.startswith(("a/", "b/")):
24
+ current_file = current_file[2:]
25
+
26
+ fixed_lines.append(line)
27
+
28
+ if line.startswith("+++ "):
29
+ try:
30
+ with open(current_file, "r", encoding="utf-8") as f:
31
+ target_content = f.read().splitlines()
32
+ except (OSError, UnicodeDecodeError):
33
+ target_content = []
34
+ elif line.strip() == "@@":
35
+ old_lines = []
36
+ j = i + 1
37
+ while j < len(lines) and not lines[j].startswith("@@") and not lines[j].startswith("---"):
38
+ if lines[j].startswith("-") or lines[j].startswith(" "):
39
+ old_lines.append(lines[j][1:])
40
+ j += 1
41
+
42
+ start_idx = 0
43
+ if old_lines and target_content:
44
+ for k in range(len(target_content) - len(old_lines) + 1):
45
+ if target_content[k : k + len(old_lines)] == old_lines:
46
+ start_idx = k
47
+ break
48
+
49
+ start_line = start_idx + 1
50
+ fixed_lines.append(f"@@ -{start_line},1 +{start_line},1 @@")
51
+ else:
52
+ fixed_lines.append(line)
53
+ i += 1
54
+
55
+ return "\n".join(fixed_lines) + "\n"
56
+
57
+
58
+ def extract_unified_diff(model_output: str) -> str:
59
+ text = model_output.strip()
60
+ fenced = re.fullmatch(r"```(?:diff|patch)?\s*\n(?P<body>.*?)\n```", text, flags=re.DOTALL)
61
+ if fenced:
62
+ text = fenced.group("body").strip()
63
+
64
+ if "\n--- " not in f"\n{text}" and "\ndiff --git " not in f"\n{text}":
65
+ raise ValueError("model did not return a unified diff")
66
+
67
+ cleaned_lines = []
68
+ for line in text.splitlines():
69
+ if line.startswith(("***", "Apply", "End of File")):
70
+ break
71
+ cleaned_lines.append(line)
72
+
73
+ cleaned_text = "\n".join(cleaned_lines)
74
+ return _fix_diff_headers(cleaned_text)
75
+
76
+
77
+ def apply_diff_python_fallback(diff_text: str) -> bool:
78
+ """
79
+ Parses a unified diff (even with bad hunk headers or extra trailing text)
80
+ and applies it directly to files on disk using fuzzy line matching.
81
+ Returns True if at least one file was modified, False otherwise.
82
+ """
83
+ lines = diff_text.splitlines()
84
+ files_hunks = {}
85
+ current_file = None
86
+ current_hunk = None
87
+
88
+ i = 0
89
+ while i < len(lines):
90
+ line = lines[i]
91
+ if line.startswith(("--- ", "+++ ")):
92
+ fname = line[4:].strip()
93
+ if fname.startswith(("a/", "b/")):
94
+ fname = fname[2:]
95
+ current_file = fname
96
+ if current_file not in files_hunks:
97
+ files_hunks[current_file] = []
98
+ elif line.startswith("@@"):
99
+ if current_hunk is not None and current_file:
100
+ files_hunks[current_file].append(current_hunk)
101
+ current_hunk = []
102
+ elif current_hunk is not None:
103
+ if line.startswith(("***", "Apply", "End of File")):
104
+ break
105
+ if line.startswith(("-", "+", " ")) or line == "":
106
+ current_hunk.append(line)
107
+ else:
108
+ current_hunk.append(" " + line)
109
+ i += 1
110
+
111
+ if current_hunk is not None and current_file:
112
+ files_hunks[current_file].append(current_hunk)
113
+
114
+ modified_any = False
115
+
116
+ for filename, hunks in files_hunks.items():
117
+ if not filename or not os.path.exists(filename):
118
+ continue
119
+
120
+ try:
121
+ with open(filename, "r", encoding="utf-8") as f:
122
+ file_content = f.read()
123
+ except (OSError, UnicodeDecodeError):
124
+ continue
125
+
126
+ file_lines = file_content.splitlines()
127
+
128
+ for hunk in hunks:
129
+ old_slice = []
130
+ new_slice = []
131
+ for hline in hunk:
132
+ if hline.startswith("-"):
133
+ old_slice.append(hline[1:])
134
+ elif hline.startswith("+"):
135
+ new_slice.append(hline[1:])
136
+ elif hline.startswith(" "):
137
+ old_slice.append(hline[1:])
138
+ new_slice.append(hline[1:])
139
+
140
+ if not old_slice:
141
+ continue
142
+
143
+ match_idx = -1
144
+ for k in range(len(file_lines) - len(old_slice) + 1):
145
+ if [l.strip() for l in file_lines[k : k + len(old_slice)]] == [l.strip() for l in old_slice]:
146
+ match_idx = k
147
+ break
148
+
149
+ if match_idx != -1:
150
+ file_lines = file_lines[:match_idx] + new_slice + file_lines[match_idx + len(old_slice) :]
151
+
152
+ updated_text = "\n".join(file_lines)
153
+ if file_content.endswith("\n"):
154
+ updated_text += "\n"
155
+
156
+ if updated_text != file_content:
157
+ with open(filename, "w", encoding="utf-8") as f:
158
+ f.write(updated_text)
159
+ modified_any = True
160
+
161
+ return modified_any
162
+
163
+
164
+ def apply_unified_diff(diff_text: str):
165
+ with tempfile.NamedTemporaryFile("w", suffix=".patch", delete=False, encoding="utf-8") as tmp:
166
+ tmp.write(diff_text)
167
+ patch_path = tmp.name
168
+
169
+ try:
170
+ check = subprocess.run(
171
+ ["git", "apply", "--unidiff-zero", "--recount", "--check", patch_path],
172
+ capture_output=True,
173
+ text=True,
174
+ check=False,
175
+ )
176
+ if check.returncode == 0:
177
+ applied = subprocess.run(
178
+ ["git", "apply", "--unidiff-zero", "--recount", patch_path], capture_output=True, text=True, check=False
179
+ )
180
+ if applied.returncode == 0:
181
+ return
182
+ except FileNotFoundError:
183
+ pass
184
+ finally:
185
+ try:
186
+ os.unlink(patch_path)
187
+ except OSError:
188
+ pass
189
+
190
+ # Fallback to Python-based fuzzy patch applier if git apply fails or is missing
191
+ success = apply_diff_python_fallback(diff_text)
192
+ if not success:
193
+ print_error("Patch apply failed. Could not match diff hunks with target file.")
194
+ raise typer.Exit(1)
195
+
196
+
197
+ def run_git(args: list[str]) -> subprocess.CompletedProcess[str]:
198
+ try:
199
+ return subprocess.run(["git", *args], capture_output=True, text=True, check=False)
200
+ except FileNotFoundError:
201
+ print_error("git is not installed on this system.")
202
+ raise typer.Exit(1)
@@ -0,0 +1,47 @@
1
+ from pathlib import Path
2
+
3
+ import pathspec
4
+
5
+ ALWAYS_IGNORED_DIRS = {
6
+ ".git",
7
+ "__pycache__",
8
+ "node_modules",
9
+ ".venv",
10
+ "venv",
11
+ "env",
12
+ ".env",
13
+ "dist",
14
+ "build",
15
+ ".next",
16
+ "target",
17
+ ".pytest_cache",
18
+ ".mypy_cache",
19
+ ".ruff_cache",
20
+ }
21
+
22
+
23
+ def get_gitignore_spec(root_dir: Path) -> pathspec.PathSpec | None:
24
+ gitignore_path = root_dir / ".gitignore"
25
+ if not gitignore_path.exists():
26
+ return None
27
+
28
+ with open(gitignore_path, "r") as f:
29
+ spec = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern, f.readlines())
30
+ return spec
31
+
32
+
33
+ def is_ignored(path: Path, root_dir: Path, spec: pathspec.PathSpec | None) -> bool:
34
+ try:
35
+ rel_path = path.relative_to(root_dir)
36
+ if any(part in ALWAYS_IGNORED_DIRS for part in rel_path.parts):
37
+ return True
38
+
39
+ if spec is None:
40
+ return False
41
+
42
+ rel = str(rel_path)
43
+ if path.is_dir() and not rel.endswith("/"):
44
+ rel += "/"
45
+ return spec.match_file(rel)
46
+ except ValueError:
47
+ return False