codeframe-ai 0.9.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 (197) hide show
  1. codeframe/__init__.py +11 -0
  2. codeframe/__main__.py +20 -0
  3. codeframe/adapters/__init__.py +5 -0
  4. codeframe/adapters/e2b/__init__.py +13 -0
  5. codeframe/adapters/e2b/adapter.py +342 -0
  6. codeframe/adapters/e2b/budget.py +71 -0
  7. codeframe/adapters/e2b/credential_scanner.py +134 -0
  8. codeframe/adapters/llm/__init__.py +92 -0
  9. codeframe/adapters/llm/anthropic.py +414 -0
  10. codeframe/adapters/llm/base.py +444 -0
  11. codeframe/adapters/llm/mock.py +281 -0
  12. codeframe/adapters/llm/openai.py +483 -0
  13. codeframe/agents/__init__.py +8 -0
  14. codeframe/agents/dependency_resolver.py +714 -0
  15. codeframe/auth/__init__.py +16 -0
  16. codeframe/auth/api_key_router.py +238 -0
  17. codeframe/auth/api_keys.py +156 -0
  18. codeframe/auth/dependencies.py +358 -0
  19. codeframe/auth/manager.py +178 -0
  20. codeframe/auth/models.py +30 -0
  21. codeframe/auth/router.py +93 -0
  22. codeframe/auth/schemas.py +15 -0
  23. codeframe/auth/scopes.py +53 -0
  24. codeframe/cli/__init__.py +12 -0
  25. codeframe/cli/__main__.py +20 -0
  26. codeframe/cli/api_client.py +275 -0
  27. codeframe/cli/app.py +5688 -0
  28. codeframe/cli/auth.py +122 -0
  29. codeframe/cli/auth_commands.py +958 -0
  30. codeframe/cli/commands/__init__.py +5 -0
  31. codeframe/cli/config_commands.py +79 -0
  32. codeframe/cli/dashboard_commands.py +67 -0
  33. codeframe/cli/engines_commands.py +205 -0
  34. codeframe/cli/env_commands.py +409 -0
  35. codeframe/cli/helpers.py +56 -0
  36. codeframe/cli/hooks_commands.py +208 -0
  37. codeframe/cli/import_commands.py +129 -0
  38. codeframe/cli/pr_commands.py +549 -0
  39. codeframe/cli/proof_commands.py +415 -0
  40. codeframe/cli/stats_commands.py +311 -0
  41. codeframe/cli/telemetry_runtime.py +153 -0
  42. codeframe/cli/validators.py +123 -0
  43. codeframe/config/rate_limits.py +165 -0
  44. codeframe/core/__init__.py +15 -0
  45. codeframe/core/adapters/__init__.py +43 -0
  46. codeframe/core/adapters/agent_adapter.py +114 -0
  47. codeframe/core/adapters/builtin.py +326 -0
  48. codeframe/core/adapters/claude_code.py +62 -0
  49. codeframe/core/adapters/codex.py +393 -0
  50. codeframe/core/adapters/git_utils.py +40 -0
  51. codeframe/core/adapters/kilocode.py +126 -0
  52. codeframe/core/adapters/opencode.py +48 -0
  53. codeframe/core/adapters/streaming_chat.py +483 -0
  54. codeframe/core/adapters/subprocess_adapter.py +213 -0
  55. codeframe/core/adapters/verification_wrapper.py +269 -0
  56. codeframe/core/agent.py +2183 -0
  57. codeframe/core/agents_config.py +569 -0
  58. codeframe/core/api_key_service.py +211 -0
  59. codeframe/core/artifacts.py +428 -0
  60. codeframe/core/blocker_detection.py +218 -0
  61. codeframe/core/blockers.py +433 -0
  62. codeframe/core/checkpoints.py +481 -0
  63. codeframe/core/conductor.py +2255 -0
  64. codeframe/core/config.py +827 -0
  65. codeframe/core/config_watcher.py +268 -0
  66. codeframe/core/context.py +542 -0
  67. codeframe/core/context_packager.py +234 -0
  68. codeframe/core/credentials.py +735 -0
  69. codeframe/core/dependency_analyzer.py +229 -0
  70. codeframe/core/dependency_graph.py +290 -0
  71. codeframe/core/diagnostic_agent.py +712 -0
  72. codeframe/core/diagnostics.py +616 -0
  73. codeframe/core/editor.py +556 -0
  74. codeframe/core/engine_registry.py +256 -0
  75. codeframe/core/engine_stats.py +231 -0
  76. codeframe/core/environment.py +697 -0
  77. codeframe/core/events.py +375 -0
  78. codeframe/core/executor.py +1005 -0
  79. codeframe/core/fix_tracker.py +480 -0
  80. codeframe/core/gates.py +1322 -0
  81. codeframe/core/git.py +477 -0
  82. codeframe/core/github_connect_service.py +178 -0
  83. codeframe/core/github_integration_config.py +118 -0
  84. codeframe/core/github_issues_service.py +449 -0
  85. codeframe/core/hooks.py +184 -0
  86. codeframe/core/importers/__init__.py +1 -0
  87. codeframe/core/importers/ralph.py +540 -0
  88. codeframe/core/installer.py +650 -0
  89. codeframe/core/models.py +1026 -0
  90. codeframe/core/notifications_config.py +183 -0
  91. codeframe/core/planner.py +437 -0
  92. codeframe/core/prd.py +670 -0
  93. codeframe/core/prd_discovery.py +1118 -0
  94. codeframe/core/prd_stress_test.py +499 -0
  95. codeframe/core/progress.py +126 -0
  96. codeframe/core/proof/__init__.py +34 -0
  97. codeframe/core/proof/capture.py +79 -0
  98. codeframe/core/proof/evidence.py +56 -0
  99. codeframe/core/proof/ledger.py +574 -0
  100. codeframe/core/proof/models.py +162 -0
  101. codeframe/core/proof/obligations.py +103 -0
  102. codeframe/core/proof/runner.py +233 -0
  103. codeframe/core/proof/scope.py +81 -0
  104. codeframe/core/proof/stubs.py +156 -0
  105. codeframe/core/quick_fixes.py +558 -0
  106. codeframe/core/react_agent.py +1650 -0
  107. codeframe/core/reconciliation.py +183 -0
  108. codeframe/core/replay.py +788 -0
  109. codeframe/core/review.py +285 -0
  110. codeframe/core/runtime.py +1134 -0
  111. codeframe/core/sandbox/__init__.py +27 -0
  112. codeframe/core/sandbox/context.py +98 -0
  113. codeframe/core/sandbox/worktree.py +20 -0
  114. codeframe/core/schedule.py +396 -0
  115. codeframe/core/stall_detector.py +71 -0
  116. codeframe/core/stall_monitor.py +134 -0
  117. codeframe/core/state_machine.py +121 -0
  118. codeframe/core/streaming.py +502 -0
  119. codeframe/core/task_tree.py +400 -0
  120. codeframe/core/tasks.py +1022 -0
  121. codeframe/core/telemetry.py +232 -0
  122. codeframe/core/templates.py +221 -0
  123. codeframe/core/tools.py +942 -0
  124. codeframe/core/workspace.py +887 -0
  125. codeframe/core/worktrees.py +276 -0
  126. codeframe/git/__init__.py +5 -0
  127. codeframe/git/github_integration.py +505 -0
  128. codeframe/lib/__init__.py +0 -0
  129. codeframe/lib/audit_logger.py +248 -0
  130. codeframe/lib/metrics_tracker.py +800 -0
  131. codeframe/lib/quality/__init__.py +7 -0
  132. codeframe/lib/quality/complexity_analyzer.py +316 -0
  133. codeframe/lib/quality/owasp_patterns.py +284 -0
  134. codeframe/lib/quality/security_scanner.py +250 -0
  135. codeframe/lib/rate_limiter.py +312 -0
  136. codeframe/notifications/__init__.py +0 -0
  137. codeframe/notifications/webhook.py +380 -0
  138. codeframe/planning/__init__.py +30 -0
  139. codeframe/planning/issue_generator.py +219 -0
  140. codeframe/planning/prd_template_functions.py +137 -0
  141. codeframe/planning/prd_templates.py +975 -0
  142. codeframe/planning/task_scheduler.py +511 -0
  143. codeframe/planning/task_templates.py +533 -0
  144. codeframe/platform_store/__init__.py +5 -0
  145. codeframe/platform_store/database.py +277 -0
  146. codeframe/platform_store/repositories/__init__.py +24 -0
  147. codeframe/platform_store/repositories/api_key_repository.py +245 -0
  148. codeframe/platform_store/repositories/audit_repository.py +67 -0
  149. codeframe/platform_store/repositories/base.py +295 -0
  150. codeframe/platform_store/repositories/interactive_sessions.py +165 -0
  151. codeframe/platform_store/repositories/token_repository.py +598 -0
  152. codeframe/platform_store/repositories/workspace_registry_repository.py +175 -0
  153. codeframe/platform_store/schema_manager.py +321 -0
  154. codeframe/templates/AGENTS.md.default +94 -0
  155. codeframe/tui/__init__.py +5 -0
  156. codeframe/tui/app.py +256 -0
  157. codeframe/tui/data_service.py +103 -0
  158. codeframe/ui/__init__.py +0 -0
  159. codeframe/ui/dependencies.py +103 -0
  160. codeframe/ui/models.py +999 -0
  161. codeframe/ui/response_models.py +201 -0
  162. codeframe/ui/routers/__init__.py +5 -0
  163. codeframe/ui/routers/_helpers.py +29 -0
  164. codeframe/ui/routers/batches_v2.py +315 -0
  165. codeframe/ui/routers/blockers_v2.py +320 -0
  166. codeframe/ui/routers/checkpoints_v2.py +310 -0
  167. codeframe/ui/routers/costs_v2.py +322 -0
  168. codeframe/ui/routers/diagnose_v2.py +225 -0
  169. codeframe/ui/routers/discovery_v2.py +417 -0
  170. codeframe/ui/routers/environment_v2.py +284 -0
  171. codeframe/ui/routers/events_v2.py +75 -0
  172. codeframe/ui/routers/gates_v2.py +166 -0
  173. codeframe/ui/routers/git_v2.py +284 -0
  174. codeframe/ui/routers/github_integrations_v2.py +532 -0
  175. codeframe/ui/routers/interactive_sessions_v2.py +238 -0
  176. codeframe/ui/routers/pr_v2.py +709 -0
  177. codeframe/ui/routers/prd_v2.py +695 -0
  178. codeframe/ui/routers/proof_v2.py +755 -0
  179. codeframe/ui/routers/review_v2.py +360 -0
  180. codeframe/ui/routers/schedule_v2.py +214 -0
  181. codeframe/ui/routers/session_chat_ws.py +354 -0
  182. codeframe/ui/routers/settings_v2.py +562 -0
  183. codeframe/ui/routers/streaming_v2.py +155 -0
  184. codeframe/ui/routers/tasks_v2.py +1098 -0
  185. codeframe/ui/routers/templates_v2.py +232 -0
  186. codeframe/ui/routers/terminal_ws.py +267 -0
  187. codeframe/ui/routers/workspace_v2.py +527 -0
  188. codeframe/ui/server.py +568 -0
  189. codeframe/ui/shared.py +241 -0
  190. codeframe/workspace/__init__.py +5 -0
  191. codeframe/workspace/manager.py +249 -0
  192. codeframe_ai-0.9.0.dist-info/METADATA +517 -0
  193. codeframe_ai-0.9.0.dist-info/RECORD +197 -0
  194. codeframe_ai-0.9.0.dist-info/WHEEL +5 -0
  195. codeframe_ai-0.9.0.dist-info/entry_points.txt +3 -0
  196. codeframe_ai-0.9.0.dist-info/licenses/LICENSE +661 -0
  197. codeframe_ai-0.9.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,311 @@
1
+ """CLI stats commands for headless token/cost tracking.
2
+
3
+ This module provides commands for viewing token usage and cost statistics
4
+ directly from the local workspace database (no server required):
5
+
6
+ - tokens: View workspace token usage summary
7
+ - costs: View cost report with optional period filtering
8
+ - export: Export usage data to CSV or JSON
9
+
10
+ Usage:
11
+ cf stats tokens # Workspace token summary
12
+ cf stats tokens --task <id> # Per-task breakdown
13
+ cf stats costs # All-time costs
14
+ cf stats costs --period month # Last 30 days
15
+ cf stats export --format csv --output tokens.csv
16
+ """
17
+
18
+ import logging
19
+ from datetime import datetime, timedelta, timezone
20
+ from pathlib import Path
21
+ from typing import Optional
22
+
23
+ import typer
24
+ from rich.table import Table
25
+
26
+ from codeframe.cli.helpers import console
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ stats_app = typer.Typer(
31
+ name="stats",
32
+ help="Token usage and cost statistics",
33
+ no_args_is_help=True,
34
+ )
35
+
36
+
37
+ def _get_db():
38
+ """Get database from current workspace.
39
+
40
+ Looks for .codeframe/state.db relative to the current directory.
41
+
42
+ Returns:
43
+ Initialized Database instance.
44
+
45
+ Raises:
46
+ typer.Exit: If no workspace is found.
47
+ """
48
+ from codeframe.platform_store.database import Database
49
+
50
+ db_path = Path(".codeframe/state.db")
51
+ if not db_path.exists():
52
+ console.print("[red]Error:[/red] No workspace found. Run 'cf init' first.")
53
+ raise typer.Exit(1)
54
+ db = Database(db_path)
55
+ db.initialize()
56
+ return db
57
+
58
+
59
+ def _get_tracker(db):
60
+ """Create a MetricsTracker from a database instance.
61
+
62
+ Args:
63
+ db: Initialized Database instance.
64
+
65
+ Returns:
66
+ MetricsTracker instance.
67
+ """
68
+ from codeframe.lib.metrics_tracker import MetricsTracker
69
+
70
+ return MetricsTracker(db=db)
71
+
72
+
73
+ def _format_number(n: int) -> str:
74
+ """Format number with thousands separator."""
75
+ return f"{n:,}"
76
+
77
+
78
+ @stats_app.command()
79
+ def tokens(
80
+ task: Optional[int] = typer.Option(
81
+ None, "--task", "-t", help="Filter by task ID for per-task breakdown"
82
+ ),
83
+ ):
84
+ """Show workspace token usage summary.
85
+
86
+ Displays total tokens used across all tasks, with input/output breakdown
87
+ and per-model statistics. Use --task to filter to a specific task.
88
+
89
+ Examples:
90
+ cf stats tokens # Workspace summary
91
+ cf stats tokens --task 1 # Task 1 breakdown
92
+ """
93
+ db = _get_db()
94
+ try:
95
+ tracker = _get_tracker(db)
96
+
97
+ if task is not None:
98
+ # Per-task summary
99
+ summary = tracker.get_task_token_summary(task)
100
+
101
+ console.print(f"\n[bold]Token Usage for Task {task}[/bold]\n")
102
+
103
+ table = Table(show_header=True, title=None)
104
+ table.add_column("Metric", style="cyan")
105
+ table.add_column("Value", justify="right")
106
+
107
+ table.add_row("Total Tokens", _format_number(summary["total_tokens"]))
108
+ table.add_row("Input Tokens", _format_number(summary["total_input_tokens"]))
109
+ table.add_row("Output Tokens", _format_number(summary["total_output_tokens"]))
110
+ table.add_row("Total Cost", f"${summary['total_cost_usd']:.4f}")
111
+ table.add_row("LLM Calls", str(summary["call_count"]))
112
+
113
+ console.print(table)
114
+ else:
115
+ # Workspace-wide summary
116
+ records = db.get_workspace_token_usage()
117
+
118
+ total_input = 0
119
+ total_output = 0
120
+ total_cost = 0.0
121
+ model_stats: dict[str, dict] = {}
122
+
123
+ for record in records:
124
+ total_input += record["input_tokens"]
125
+ total_output += record["output_tokens"]
126
+ total_cost += record["estimated_cost_usd"]
127
+
128
+ model = record["model_name"]
129
+ if model not in model_stats:
130
+ model_stats[model] = {
131
+ "input_tokens": 0,
132
+ "output_tokens": 0,
133
+ "cost_usd": 0.0,
134
+ "calls": 0,
135
+ }
136
+ model_stats[model]["input_tokens"] += record["input_tokens"]
137
+ model_stats[model]["output_tokens"] += record["output_tokens"]
138
+ model_stats[model]["cost_usd"] += record["estimated_cost_usd"]
139
+ model_stats[model]["calls"] += 1
140
+
141
+ total_tokens = total_input + total_output
142
+
143
+ console.print("\n[bold]Workspace Token Usage Summary[/bold]\n")
144
+
145
+ summary_table = Table(show_header=True)
146
+ summary_table.add_column("Metric", style="cyan")
147
+ summary_table.add_column("Value", justify="right")
148
+
149
+ summary_table.add_row("Total Tokens", _format_number(total_tokens))
150
+ summary_table.add_row("Input Tokens", _format_number(total_input))
151
+ summary_table.add_row("Output Tokens", _format_number(total_output))
152
+ summary_table.add_row("Total Cost", f"${total_cost:.4f}")
153
+ summary_table.add_row("LLM Calls", str(len(records)))
154
+
155
+ console.print(summary_table)
156
+
157
+ if model_stats:
158
+ console.print("\n[bold]By Model:[/bold]")
159
+ model_table = Table(show_header=True)
160
+ model_table.add_column("Model", style="cyan")
161
+ model_table.add_column("Tokens", justify="right")
162
+ model_table.add_column("Cost", justify="right")
163
+ model_table.add_column("Calls", justify="right")
164
+
165
+ for model_name, stats in model_stats.items():
166
+ model_table.add_row(
167
+ model_name,
168
+ _format_number(stats["input_tokens"] + stats["output_tokens"]),
169
+ f"${stats['cost_usd']:.4f}",
170
+ str(stats["calls"]),
171
+ )
172
+
173
+ console.print(model_table)
174
+ finally:
175
+ db.close()
176
+
177
+
178
+ @stats_app.command()
179
+ def costs(
180
+ period: Optional[str] = typer.Option(
181
+ None,
182
+ "--period",
183
+ "-p",
184
+ help="Time period: 'day' (24h), 'week' (7d), 'month' (30d)",
185
+ ),
186
+ ):
187
+ """Show cost report.
188
+
189
+ Displays total costs and per-model breakdown. Use --period to filter
190
+ to a recent time window.
191
+
192
+ Examples:
193
+ cf stats costs # All-time costs
194
+ cf stats costs --period month # Last 30 days
195
+ cf stats costs --period week # Last 7 days
196
+ cf stats costs --period day # Last 24 hours
197
+ """
198
+ db = _get_db()
199
+ try:
200
+ # Calculate date range from period
201
+ start_date = None
202
+ end_date = None
203
+ now = datetime.now(timezone.utc)
204
+
205
+ if period == "day":
206
+ start_date = now - timedelta(days=1)
207
+ elif period == "week":
208
+ start_date = now - timedelta(weeks=1)
209
+ elif period == "month":
210
+ start_date = now - timedelta(days=30)
211
+ elif period is not None:
212
+ console.print(
213
+ f"[red]Error:[/red] Unknown period '{period}'. Use 'day', 'week', or 'month'."
214
+ )
215
+ raise typer.Exit(1)
216
+
217
+ # Single fetch: get raw records and compute summary + per-model breakdown in one pass
218
+ records = db.get_workspace_token_usage(start_date=start_date, end_date=end_date)
219
+
220
+ total_cost = 0.0
221
+ total_tokens = 0
222
+ model_costs: dict[str, dict] = {}
223
+ for record in records:
224
+ cost = record["estimated_cost_usd"]
225
+ tokens = record["input_tokens"] + record["output_tokens"]
226
+ total_cost += cost
227
+ total_tokens += tokens
228
+
229
+ model = record["model_name"]
230
+ if model not in model_costs:
231
+ model_costs[model] = {"cost_usd": 0.0, "tokens": 0, "calls": 0}
232
+ model_costs[model]["cost_usd"] += cost
233
+ model_costs[model]["tokens"] += tokens
234
+ model_costs[model]["calls"] += 1
235
+
236
+ period_label = f" ({period})" if period else " (all time)"
237
+ console.print(f"\n[bold]Cost Report{period_label}[/bold]\n")
238
+
239
+ table = Table(show_header=True)
240
+ table.add_column("Metric", style="cyan")
241
+ table.add_column("Value", justify="right")
242
+
243
+ table.add_row("Total Cost", f"${total_cost:.4f}")
244
+ table.add_row("Total Tokens", _format_number(total_tokens))
245
+ table.add_row("LLM Calls", str(len(records)))
246
+
247
+ console.print(table)
248
+
249
+ if model_costs:
250
+ console.print("\n[bold]By Model:[/bold]")
251
+ model_table = Table(show_header=True)
252
+ model_table.add_column("Model", style="cyan")
253
+ model_table.add_column("Cost", justify="right")
254
+ model_table.add_column("Tokens", justify="right")
255
+ model_table.add_column("Calls", justify="right")
256
+
257
+ for model_name, stats in model_costs.items():
258
+ model_table.add_row(
259
+ model_name,
260
+ f"${stats['cost_usd']:.4f}",
261
+ _format_number(stats["tokens"]),
262
+ str(stats["calls"]),
263
+ )
264
+
265
+ console.print(model_table)
266
+ finally:
267
+ db.close()
268
+
269
+
270
+ @stats_app.command("export")
271
+ def export_data(
272
+ format: str = typer.Option(
273
+ "csv", "--format", "-f", help="Output format: csv or json"
274
+ ),
275
+ output: str = typer.Option(
276
+ ..., "--output", "-o", help="Output file path"
277
+ ),
278
+ task: Optional[int] = typer.Option(
279
+ None, "--task", "-t", help="Filter by task ID"
280
+ ),
281
+ ):
282
+ """Export usage data to CSV or JSON.
283
+
284
+ Exports raw token usage records to a file for external analysis.
285
+ Use --task to export records for a single task only.
286
+
287
+ Examples:
288
+ cf stats export --format csv --output tokens.csv
289
+ cf stats export --format json --output tokens.json
290
+ cf stats export --format csv --output task1.csv --task 1
291
+ """
292
+ from codeframe.lib.metrics_tracker import MetricsTracker
293
+
294
+ db = _get_db()
295
+ try:
296
+ if task is not None:
297
+ records = db.get_batch_token_usage(task_ids=[task])
298
+ else:
299
+ records = db.get_workspace_token_usage()
300
+
301
+ if format == "csv":
302
+ MetricsTracker.export_to_csv(records, output)
303
+ elif format == "json":
304
+ MetricsTracker.export_to_json(records, output)
305
+ else:
306
+ console.print(f"[red]Error:[/red] Unknown format '{format}'. Use 'csv' or 'json'.")
307
+ raise typer.Exit(1)
308
+
309
+ console.print(f"Exported {len(records)} records to {output}")
310
+ finally:
311
+ db.close()
@@ -0,0 +1,153 @@
1
+ """Telemetry-aware CLI entry wrapper (issue #616).
2
+
3
+ Wraps the Typer app to provide: the one-time opt-in prompt, command timing,
4
+ success/failure capture, and crash reporting. Telemetry can never change the
5
+ CLI's behavior — every telemetry step is best-effort and silent on failure,
6
+ and the wrapped app's exit code / exception always propagates unchanged.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import os
13
+ import sys
14
+ import time
15
+ from typing import Optional
16
+
17
+ import click
18
+ import typer
19
+ import typer.main
20
+ from rich.console import Console
21
+
22
+ from codeframe.core import telemetry
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ console = Console()
27
+
28
+ # Bounded wait for the fire-and-forget send at process exit. Worst case this
29
+ # adds 1s to an opted-in command; opted-out commands are unaffected.
30
+ _SEND_JOIN_SECONDS = 1.0
31
+
32
+
33
+ def _is_interactive() -> bool:
34
+ return sys.stdin.isatty() and sys.stdout.isatty()
35
+
36
+
37
+ def resolve_command_name(cli_app: typer.Typer, args: list[str]) -> Optional[str]:
38
+ """Map argv tokens to a registered command path ("work batch run").
39
+
40
+ Only names that exist in the command tree are ever returned — arbitrary
41
+ user tokens (file paths, task ids, typos) can never leak into telemetry.
42
+ Returns None when no command token is present (bare ``cf`` / ``--help``),
43
+ and "unknown" when the first token matches nothing.
44
+ """
45
+ group = typer.main.get_command(cli_app)
46
+ path: list[str] = []
47
+ for token in args:
48
+ if token.startswith("-"):
49
+ continue
50
+ if not isinstance(group, click.Group):
51
+ break
52
+ command = group.commands.get(token)
53
+ if command is None:
54
+ break
55
+ path.append(token)
56
+ group = command
57
+ if path:
58
+ return " ".join(path)
59
+ has_positional = any(not t.startswith("-") for t in args)
60
+ return "unknown" if has_positional else None
61
+
62
+
63
+ def maybe_prompt_first_run(args: list[str]) -> None:
64
+ """One-time opt-in prompt (default No). Skipped when non-interactive, when
65
+ an env override is active, when already prompted, and during ``cf config``."""
66
+ try:
67
+ if not args or args[0].startswith("-") or args[0] == "config":
68
+ return
69
+ if telemetry.env_override() is not None:
70
+ return
71
+ if os.environ.get("DO_NOT_TRACK", "").strip().lower() not in ("", "0", "false"):
72
+ return
73
+ if not _is_interactive():
74
+ return
75
+ config = telemetry.load_config()
76
+ if config.prompted:
77
+ return
78
+ console.print(
79
+ "\n[bold]Help improve CodeFRAME?[/bold] Share anonymous usage events and "
80
+ "crash reports (command name, duration, version, OS — never code, "
81
+ "prompts, or file paths). Details: PRIVACY.md. "
82
+ "Change anytime: [cyan]cf config telemetry on|off[/cyan]"
83
+ )
84
+ answer = typer.confirm("Enable anonymous telemetry?", default=False)
85
+ config.enabled = answer
86
+ config.prompted = True
87
+ telemetry.save_config(config)
88
+ console.print()
89
+ except (click.Abort, KeyboardInterrupt):
90
+ raise
91
+ except Exception:
92
+ logger.debug("Telemetry first-run prompt failed", exc_info=True)
93
+
94
+
95
+ def _coerce_exit_code(code: object) -> int:
96
+ if code is None:
97
+ return 0
98
+ if isinstance(code, int):
99
+ return code
100
+ return 1
101
+
102
+
103
+ def _dispatch(
104
+ command: Optional[str],
105
+ start: float,
106
+ exit_code: int,
107
+ crash: Optional[BaseException] = None,
108
+ ) -> None:
109
+ """Build and send events for this invocation. Never raises."""
110
+ try:
111
+ if command is None or not telemetry.is_enabled():
112
+ return
113
+ config = telemetry.ensure_config()
114
+ duration_ms = int((time.monotonic() - start) * 1000)
115
+ events = [
116
+ telemetry.build_command_event(
117
+ command=command,
118
+ duration_ms=duration_ms,
119
+ exit_code=exit_code,
120
+ anonymous_id=config.anonymous_id,
121
+ )
122
+ ]
123
+ if crash is not None:
124
+ events.append(telemetry.build_crash_event(crash, config.anonymous_id))
125
+ thread = telemetry.send_events_background(events, telemetry.resolve_endpoint())
126
+ thread.join(_SEND_JOIN_SECONDS)
127
+ except Exception:
128
+ logger.debug("Telemetry dispatch failed", exc_info=True)
129
+
130
+
131
+ def run(cli_app: typer.Typer) -> None:
132
+ """Run the Typer app with telemetry instrumentation around it."""
133
+ args = sys.argv[1:]
134
+ maybe_prompt_first_run(args)
135
+ command = resolve_command_name(cli_app, args)
136
+ start = time.monotonic()
137
+ try:
138
+ cli_app(prog_name="codeframe")
139
+ except SystemExit as e:
140
+ _dispatch(command, start, _coerce_exit_code(e.code))
141
+ raise
142
+ except (KeyboardInterrupt, click.Abort):
143
+ _dispatch(command, start, 130)
144
+ raise
145
+ except BaseException as e:
146
+ # Unhandled crash: record it, then let it propagate so Typer's
147
+ # excepthook still prints the traceback and the exit code is unchanged.
148
+ _dispatch(command, start, 1, crash=e)
149
+ raise
150
+ else:
151
+ # Click standalone mode normally exits via SystemExit; cover the
152
+ # non-standalone path for completeness.
153
+ _dispatch(command, start, 0)
@@ -0,0 +1,123 @@
1
+ """CLI validation helpers for pre-command checks."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ import typer
7
+ from dotenv import load_dotenv
8
+ from rich.console import Console
9
+
10
+ console = Console()
11
+
12
+
13
+ def require_anthropic_api_key() -> str:
14
+ """Ensure ANTHROPIC_API_KEY is available, loading from .env if needed.
15
+
16
+ Checks os.environ first. If not found, attempts to load from .env files
17
+ (~/.env as base, then cwd/.env with override). If found after loading,
18
+ sets in os.environ so subprocesses inherit it.
19
+
20
+ Returns:
21
+ The API key string.
22
+
23
+ Raises:
24
+ typer.Exit: If the key cannot be found anywhere.
25
+ """
26
+ key = os.getenv("ANTHROPIC_API_KEY")
27
+ if key:
28
+ return key
29
+
30
+ # Try loading from .env files (same priority as app.py)
31
+ cwd_env = Path.cwd() / ".env"
32
+ home_env = Path.home() / ".env"
33
+
34
+ if home_env.exists():
35
+ load_dotenv(home_env)
36
+ if cwd_env.exists():
37
+ load_dotenv(cwd_env, override=True)
38
+
39
+ key = os.getenv("ANTHROPIC_API_KEY")
40
+ if key:
41
+ os.environ["ANTHROPIC_API_KEY"] = key
42
+ return key
43
+
44
+ console.print(
45
+ "[red]Error:[/red] ANTHROPIC_API_KEY is not set. "
46
+ "Set it in your environment or add it to a .env file."
47
+ )
48
+ raise typer.Exit(1)
49
+
50
+
51
+ def require_openai_api_key() -> str:
52
+ """Ensure OPENAI_API_KEY is available, loading from .env if needed.
53
+
54
+ Checks os.environ first. If not found, attempts to load from .env files
55
+ (~/.env as base, then cwd/.env with override). If found after loading,
56
+ sets in os.environ so subprocesses inherit it.
57
+
58
+ Returns:
59
+ The API key string.
60
+
61
+ Raises:
62
+ typer.Exit: If the key cannot be found anywhere.
63
+ """
64
+ key = os.getenv("OPENAI_API_KEY")
65
+ if key:
66
+ return key
67
+
68
+ cwd_env = Path.cwd() / ".env"
69
+ home_env = Path.home() / ".env"
70
+
71
+ if home_env.exists():
72
+ load_dotenv(home_env)
73
+ if cwd_env.exists():
74
+ load_dotenv(cwd_env, override=True)
75
+
76
+ key = os.getenv("OPENAI_API_KEY")
77
+ if key:
78
+ os.environ["OPENAI_API_KEY"] = key
79
+ return key
80
+
81
+ console.print(
82
+ "[red]Error:[/red] OPENAI_API_KEY is not set. "
83
+ "Set it in your environment or add it to a .env file."
84
+ )
85
+ raise typer.Exit(1)
86
+
87
+
88
+ def require_e2b_api_key() -> str:
89
+ """Ensure E2B_API_KEY is available, loading from .env if needed.
90
+
91
+ Checks os.environ first. If not found, attempts to load from .env files
92
+ (~/.env as base, then cwd/.env with override). If found after loading,
93
+ sets in os.environ so subprocesses inherit it.
94
+
95
+ Returns:
96
+ The API key string.
97
+
98
+ Raises:
99
+ typer.Exit: If the key cannot be found anywhere.
100
+ """
101
+ key = os.getenv("E2B_API_KEY")
102
+ if key:
103
+ return key
104
+
105
+ cwd_env = Path.cwd() / ".env"
106
+ home_env = Path.home() / ".env"
107
+
108
+ if home_env.exists():
109
+ load_dotenv(home_env)
110
+ if cwd_env.exists():
111
+ load_dotenv(cwd_env, override=True)
112
+
113
+ key = os.getenv("E2B_API_KEY")
114
+ if key:
115
+ os.environ["E2B_API_KEY"] = key
116
+ return key
117
+
118
+ console.print(
119
+ "[red]Error:[/red] E2B_API_KEY is not set. "
120
+ "Set it in your environment or add it to a .env file. "
121
+ "Get your key at https://e2b.dev"
122
+ )
123
+ raise typer.Exit(1)