k-cli-for-devs 1.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 (75) hide show
  1. k_cli/__init__.py +77 -0
  2. k_cli/agents/__init__.py +0 -0
  3. k_cli/agents/adversarial_swarm.py +338 -0
  4. k_cli/agents/agent_core.py +255 -0
  5. k_cli/agents/background_daemon.py +141 -0
  6. k_cli/agents/orchestrator.py +376 -0
  7. k_cli/agents/persona.py +649 -0
  8. k_cli/agents/scaffold_engine.py +121 -0
  9. k_cli/agents/strands_agent.py +832 -0
  10. k_cli/agents/subagents.py +1496 -0
  11. k_cli/cli.py +3297 -0
  12. k_cli/core/__init__.py +0 -0
  13. k_cli/core/airgap.py +95 -0
  14. k_cli/core/credentials.py +548 -0
  15. k_cli/core/intent_sensor.py +177 -0
  16. k_cli/core/llm_driver.py +1028 -0
  17. k_cli/core/model_manager.py +1109 -0
  18. k_cli/core/models_hub.py +913 -0
  19. k_cli/core/prompting.py +41 -0
  20. k_cli/core/sdk.py +322 -0
  21. k_cli/core/session.py +826 -0
  22. k_cli/core/smart_router.py +230 -0
  23. k_cli/core/storage_manager.py +176 -0
  24. k_cli/core/viewport_engine.py +117 -0
  25. k_cli/demo/demo_runner.py +579 -0
  26. k_cli/git/__init__.py +0 -0
  27. k_cli/git/ai_bisect.py +208 -0
  28. k_cli/git/conflict_resolver.py +1039 -0
  29. k_cli/git/git_guard.py +417 -0
  30. k_cli/git/patcher.py +1175 -0
  31. k_cli/git/repo_map.py +1780 -0
  32. k_cli/git/smart_git.py +928 -0
  33. k_cli/git/verifier.py +969 -0
  34. k_cli/github/__init__.py +0 -0
  35. k_cli/github/dedup_engine.py +787 -0
  36. k_cli/github/github_client.py +1702 -0
  37. k_cli/github/github_engine.py +641 -0
  38. k_cli/github/local_hub.py +209 -0
  39. k_cli/github/pr_watcher.py +129 -0
  40. k_cli/github/trending.py +205 -0
  41. k_cli/tools/__init__.py +0 -0
  42. k_cli/tools/audit.py +79 -0
  43. k_cli/tools/chaos_immunity.py +377 -0
  44. k_cli/tools/codebase_qa.py +106 -0
  45. k_cli/tools/command_runner.py +256 -0
  46. k_cli/tools/diagram_generator.py +547 -0
  47. k_cli/tools/doc_retriever.py +1332 -0
  48. k_cli/tools/feature.py +105 -0
  49. k_cli/tools/ghost_daemon.py +122 -0
  50. k_cli/tools/incident_triage.py +1365 -0
  51. k_cli/tools/mcp_client.py +1846 -0
  52. k_cli/tools/repo_gardener.py +142 -0
  53. k_cli/tools/rules.py +109 -0
  54. k_cli/tools/security.py +52 -0
  55. k_cli/tools/security_healer.py +999 -0
  56. k_cli/tools/synapse_graph.py +155 -0
  57. k_cli/tui/__init__.py +0 -0
  58. k_cli/tui/diff_viewer.py +223 -0
  59. k_cli/tui/tui.py +1145 -0
  60. k_cli/tui/tui_animations.py +648 -0
  61. k_cli/tui/tui_app.py +2788 -0
  62. k_cli/ui/__init__.py +10 -0
  63. k_cli/ui/simple_repl.py +315 -0
  64. k_cli/web/__init__.py +7 -0
  65. k_cli/web/server.py +624 -0
  66. k_cli/web/static/app.js +830 -0
  67. k_cli/web/static/index.html +495 -0
  68. k_cli/web/static/monitor.html +189 -0
  69. k_cli/web/static/style.css +838 -0
  70. k_cli_for_devs-1.0.0.dist-info/METADATA +461 -0
  71. k_cli_for_devs-1.0.0.dist-info/RECORD +75 -0
  72. k_cli_for_devs-1.0.0.dist-info/WHEEL +5 -0
  73. k_cli_for_devs-1.0.0.dist-info/entry_points.txt +2 -0
  74. k_cli_for_devs-1.0.0.dist-info/licenses/LICENSE +21 -0
  75. k_cli_for_devs-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,41 @@
1
+ """Provider-aware prompt scaffolding used by K-CLI commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class ModelProfile:
10
+ name: str
11
+ strengths: str
12
+ response_contract: str
13
+
14
+
15
+ PROFILES = {
16
+ "gemini": ModelProfile("Gemini", "large-context analysis and implementation", "State assumptions, then emit one implementation."),
17
+ "claude": ModelProfile("Claude", "careful design, refactoring, and review", "Prefer a small, reviewable diff with explicit trade-offs."),
18
+ "openai": ModelProfile("OpenAI-compatible", "tool-oriented coding and concise execution", "Work from repository evidence and keep the final answer concise."),
19
+ "deepseek": ModelProfile("DeepSeek", "reasoning-heavy algorithmic and coding tasks", "Check edge cases and return executable code."),
20
+ "ollama": ModelProfile("Local model", "focused local code generation", "Use short context, concrete constraints, and one self-contained answer."),
21
+ "default": ModelProfile("Generic model", "general software engineering", "Return a minimal, testable implementation."),
22
+ }
23
+
24
+
25
+ def resolve_profile(model_name: str) -> ModelProfile:
26
+ name = (model_name or "").lower()
27
+ for key, profile in PROFILES.items():
28
+ if key != "default" and key in name:
29
+ return profile
30
+ return PROFILES["ollama"] if ":" in name else PROFILES["default"]
31
+
32
+
33
+ def enhance_prompt(task: str, model_name: str, language: str = "python") -> str:
34
+ """Add a short provider-specific execution contract without changing user intent."""
35
+ profile = resolve_profile(model_name)
36
+ return (
37
+ f"You are using {profile.name}. Your strength for this task is {profile.strengths}.\n"
38
+ f"Target language: {language}. {profile.response_contract}\n"
39
+ "Respect existing APIs, avoid unrelated rewrites, and make acceptance criteria observable.\n\n"
40
+ f"Task: {task}"
41
+ )
k_cli/core/sdk.py ADDED
@@ -0,0 +1,322 @@
1
+ """
2
+ sdk.py - Universal Python SDK & Agentic Framework for K-CLI
3
+ Project Bankai Engine v1.0.0
4
+
5
+ Provides a clean, unified Python API for programmatic integration:
6
+ ```python
7
+ from k_cli import KCLI
8
+
9
+ # 1. Initialize K-CLI Agent
10
+ with KCLI(model="deepseek-reasoner", local_fallback="qwen2.5-coder:1.5b") as kcli:
11
+ # 2. Multi-Model Inference
12
+ response = kcli.generate("Write a lock-free queue in C++23")
13
+
14
+ # 3. Autonomous GitHub Agent
15
+ kcli.github.solve_issue(12, auto_pr=True)
16
+ kcli.github.create_release(tag_name="v1.0.0")
17
+
18
+ # 4. Conflict Resolution & Security Healing
19
+ kcli.conflicts.resolve_all()
20
+ kcli.security.heal_all()
21
+
22
+ # 5. Visual Architecture Diagrams
23
+ kcli.diagrams.generate_mermaid_architecture(output_file="ARCHITECTURE.md")
24
+ ```
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import logging
30
+ from pathlib import Path
31
+ from typing import Any, Callable, Dict, List, Optional, Union
32
+
33
+ from k_cli.core.llm_driver import LLMDriver, ProviderType
34
+ from k_cli.core.models_hub import ModelBenchmarkResult, ModelHub, ModelSpec
35
+ from k_cli.github.github_engine import GitHubEngine, IssueSolveResult
36
+ from k_cli.github.github_client import GitHubClient, PRLifecycleManager
37
+ from k_cli.git.conflict_resolver import ConflictResolver, ConflictSummary
38
+ from k_cli.github.dedup_engine import DedupEngine, DedupMatch
39
+ from k_cli.tools.mcp_client import MCPManager
40
+ from k_cli.tools.incident_triage import IncidentHealResult, IncidentReport, IncidentTriageEngine
41
+ from k_cli.tools.diagram_generator import DiagramGenerator
42
+ from k_cli.git.smart_git import SmartCommitProposal, SmartGitEngine
43
+ from k_cli.tools.security_healer import SecurityHealer, VulnerabilityHealResult, SecurityScanReport
44
+ from k_cli.git.verifier import Verifier
45
+ from k_cli.git.patcher import Patcher
46
+ from k_cli.agents.orchestrator import Orchestrator, OrchestratorResult
47
+ from k_cli.core.session import SessionManager
48
+ from dataclasses import dataclass, field
49
+
50
+
51
+ @dataclass
52
+ class PlanResult:
53
+ """Result of a planning operation with optional deduplication warning."""
54
+ goal: str
55
+ steps: List[str] = field(default_factory=list)
56
+ dedup_warning: Optional[str] = None
57
+ dedup_match: Optional[Dict[str, Any]] = None
58
+
59
+ workspace: Optional[Path] = None
60
+ relevant_files: List[str] = field(default_factory=list)
61
+ detected_tools: List[str] = field(default_factory=list)
62
+ repo_map: str = ""
63
+ project_guidance: Optional[str] = None
64
+
65
+ def render_markdown(self) -> str:
66
+ """Render the plan as a markdown string."""
67
+ lines = ["# protected plan", f"## Plan: {self.goal}", ""]
68
+ if self.project_guidance:
69
+ lines += ["### Project guidance", self.project_guidance, ""]
70
+ for i, step in enumerate(self.steps, 1):
71
+ lines.append(f"{i}. {step}")
72
+ if self.dedup_warning:
73
+ lines += ["", f"> **Deduplication warning**: {self.dedup_warning}"]
74
+ return "\n".join(lines)
75
+
76
+
77
+ def create_plan(
78
+ goal: str,
79
+ workspace_dir: Union[str, Path] = ".",
80
+ max_files: int = 10,
81
+ ) -> PlanResult:
82
+ """Generate a protected, read-only change plan with deduplication check."""
83
+ workspace_path = Path(workspace_dir).resolve()
84
+ dedup = DedupEngine()
85
+ match = dedup.scan_for_duplicate(query=goal, repo_path=str(workspace_path))
86
+ warning = None
87
+ match_info = None
88
+ if match and match.is_duplicate and match.confidence > 0.6:
89
+ warning = f"Similar work detected (confidence {match.confidence:.0%}): {match.explanation}"
90
+ match_info = {"is_duplicate": True, "confidence": match.confidence, "explanation": match.explanation}
91
+ steps = [
92
+ f"Analyse codebase and understand context for: {goal}",
93
+ "Identify files and modules that need to change",
94
+ "Generate a minimal surgical diff",
95
+ "Verify changes with AST parser and project tests",
96
+ "Commit with conventional message and open PR",
97
+ ]
98
+ return PlanResult(
99
+ goal=goal,
100
+ steps=steps,
101
+ dedup_warning=warning,
102
+ dedup_match=match_info,
103
+ workspace=workspace_path,
104
+ )
105
+
106
+ logger = logging.getLogger("k_cli.sdk")
107
+
108
+
109
+ class KCLI:
110
+ """
111
+ Main K-CLI Agentic SDK Client.
112
+ Provides direct programmatic access to all local & cloud AI models,
113
+ autonomous GitHub operations, merge conflict resolvers, and security healers.
114
+ """
115
+
116
+ def __init__(
117
+ self,
118
+ model: str = "qwen2.5-coder:1.5b",
119
+ provider: Optional[Union[ProviderType, str]] = None,
120
+ repo_path: str = ".",
121
+ mock_mode: bool = False,
122
+ github_token: Optional[str] = None,
123
+ ram_budget_mb: float = 1024.0,
124
+ ):
125
+ self.repo_path = Path(repo_path).resolve()
126
+ self.active_model_name = model
127
+ self.mock_mode = mock_mode
128
+
129
+ # Core Engines
130
+ self.models = ModelHub()
131
+ self.verifier = Verifier()
132
+ self.patcher = Patcher()
133
+ self.driver = LLMDriver(
134
+ model_name=model,
135
+ provider=provider,
136
+ mock_mode=mock_mode,
137
+ )
138
+ self.dedup = DedupEngine(repo_path=str(self.repo_path))
139
+ self.orchestrator = Orchestrator(
140
+ driver=self.driver,
141
+ verifier=self.verifier,
142
+ dedup_engine=self.dedup,
143
+ ram_budget_mb=ram_budget_mb,
144
+ )
145
+ self.session = SessionManager(
146
+ workspace_dir=str(self.repo_path),
147
+ model_name=model,
148
+ mock_mode=mock_mode,
149
+ )
150
+
151
+ # Specialized Tooling
152
+ self.github = GitHubEngine(token=github_token, repo_path=str(self.repo_path))
153
+ self.pr_lifecycle = PRLifecycleManager(client=GitHubClient(token=github_token))
154
+ self.github.client = self.pr_lifecycle.client
155
+ self.conflicts = ConflictResolver()
156
+ self.mcp = MCPManager()
157
+ self.security = SecurityHealer(repo_path=str(self.repo_path), llm_driver=self.driver)
158
+ self.triage = IncidentTriageEngine(repo_path=str(self.repo_path))
159
+ self.diagrams = DiagramGenerator(repo_path=str(self.repo_path))
160
+ self.smart_git = SmartGitEngine(repo_path=str(self.repo_path), llm_driver=self.driver)
161
+
162
+ def __enter__(self) -> KCLI:
163
+ return self
164
+
165
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
166
+ pass
167
+
168
+ # =========================================================================
169
+ # High-Level Agent Methods
170
+ # =========================================================================
171
+
172
+ def generate(
173
+ self,
174
+ prompt: str,
175
+ model: Optional[str] = None,
176
+ system_prompt: Optional[str] = None,
177
+ stream_callback: Optional[Callable[[str], None]] = None,
178
+ ) -> str:
179
+ """Generates AI response across any local or cloud model."""
180
+ target_driver = self.driver
181
+ if model and model != self.active_model_name:
182
+ target_driver = LLMDriver(model_name=model, mock_mode=self.mock_mode)
183
+
184
+ return target_driver.generate(
185
+ prompt=prompt,
186
+ system_prompt=system_prompt,
187
+ stream_callback=stream_callback,
188
+ )
189
+
190
+ def run(
191
+ self,
192
+ task: str,
193
+ language: str = "python",
194
+ test_code: Optional[str] = None,
195
+ stream_callback: Optional[Callable[[Any, str], None]] = None,
196
+ ) -> OrchestratorResult:
197
+ """Executes full verified 5-stage persona pipeline."""
198
+ return self.orchestrator.execute_pipeline(
199
+ user_prompt=task,
200
+ language=language,
201
+ test_code=test_code,
202
+ token_stream_callback=stream_callback,
203
+ )
204
+
205
+ def plan(self, goal: str, max_files: int = 10) -> PlanResult:
206
+ """Generates a protected, read-only change plan with deduplication check."""
207
+ return create_plan(
208
+ goal=goal,
209
+ workspace_dir=str(self.repo_path),
210
+ max_files=max_files,
211
+ )
212
+
213
+ def resolve_conflicts(self, repo_path: Optional[str] = None) -> ConflictSummary:
214
+ """Automatically resolves all git merge conflicts with compiler verification."""
215
+ target_path = repo_path or str(self.repo_path)
216
+ return self.conflicts.resolve_all_conflicts(
217
+ repo_path=target_path,
218
+ llm_driver=self.driver,
219
+ verifier=self.verifier,
220
+ )
221
+
222
+ def solve_issue(self, issue_number: int, auto_pr: bool = True) -> IssueSolveResult:
223
+ """Autonomously investigates, fixes, verifies, and PRs a GitHub issue."""
224
+ return self.github.solve_issue(
225
+ issue_number=issue_number,
226
+ llm_driver=self.driver,
227
+ verifier=self.verifier,
228
+ patcher=self.patcher,
229
+ auto_pr=auto_pr,
230
+ )
231
+
232
+ def scan_security(self) -> SecurityScanReport:
233
+ """Scans repository for security vulnerabilities."""
234
+ return self.security.scan_repository()
235
+
236
+ def heal_security(self) -> List[VulnerabilityHealResult]:
237
+ """Scans and surgically auto-heals security vulnerabilities."""
238
+ return self.security.heal_all_vulnerabilities(
239
+ verifier=self.verifier,
240
+ patcher=self.patcher,
241
+ llm_driver=self.driver,
242
+ )
243
+
244
+ def generate_diagram(self, output_file: Optional[str] = None) -> str:
245
+ """Generates visual Mermaid architecture diagrams."""
246
+ return self.diagrams.generate_mermaid_architecture(output_file=output_file)
247
+
248
+ def commit(self, push: bool = False) -> SmartCommitProposal:
249
+ """Generates AST Conventional Commit and optionally pushes."""
250
+ proposal = self.smart_git.generate_smart_commit()
251
+ if proposal.subject:
252
+ self.smart_git.auto_stage_and_commit(message=proposal.full_message, push=push)
253
+ return proposal
254
+
255
+ # =========================================================================
256
+ # 10 Killer Agentic Features
257
+ # =========================================================================
258
+
259
+ def watch_prs(self, interval_seconds: int = 30, max_iterations: Optional[int] = 1, auto_merge: bool = False) -> List[Any]:
260
+ """Feature 1: Autonomous PR Review & Watcher Daemon."""
261
+ from k_cli.github.pr_watcher import PRWatcherDaemon
262
+ daemon = PRWatcherDaemon(
263
+ repo_path=str(self.repo_path),
264
+ github_client=self.github.client if hasattr(self.github, "client") else None,
265
+ llm_driver=self.driver,
266
+ auto_merge_approved=auto_merge,
267
+ )
268
+ return daemon.run_loop(interval_seconds=interval_seconds, max_iterations=max_iterations)
269
+
270
+ def bisect(self, test_command: str = "pytest tests/ -q", good_commit: str = "HEAD~5", bad_commit: str = "HEAD") -> Any:
271
+ """Feature 2: AI-Powered Git Bisect & Regression Hunter."""
272
+ from k_cli.git.ai_bisect import AIBisectEngine
273
+ engine = AIBisectEngine(repo_path=str(self.repo_path), llm_driver=self.driver, verifier=self.verifier, patcher=self.patcher)
274
+ return engine.run_bisect(test_command=test_command, good_commit=good_commit, bad_commit=bad_commit)
275
+
276
+ def route(self, task_prompt: str) -> Any:
277
+ """Feature 3: Cost & Latency Smart Model Router."""
278
+ from k_cli.core.smart_router import SmartModelRouter
279
+ router = SmartModelRouter(hub=self.models)
280
+ return router.route(task_prompt=task_prompt)
281
+
282
+ def garden(self) -> Any:
283
+ """Feature 4: Nightly Autonomous Repo Maintenance & Health Engine."""
284
+ from k_cli.tools.repo_gardener import RepoGardener
285
+ gardener = RepoGardener(repo_path=str(self.repo_path))
286
+ return gardener.run_garden_sweep()
287
+
288
+ def explain(self, query: str) -> Any:
289
+ """Feature 5: Codebase Natural Language Search & Semantic Q&A."""
290
+ from k_cli.tools.codebase_qa import CodebaseQAEngine
291
+ qa = CodebaseQAEngine(repo_path=str(self.repo_path), llm_driver=self.driver)
292
+ return qa.ask(query=query)
293
+
294
+ def ghost(self, command_str: str) -> int:
295
+ """Feature 6: Ghost Terminal Autopilot & Error Healer Daemon."""
296
+ from k_cli.tools.ghost_daemon import GhostTerminalDaemon
297
+ ghost_d = GhostTerminalDaemon(repo_path=str(self.repo_path), llm_driver=self.driver, verifier=self.verifier, patcher=self.patcher)
298
+ return ghost_d.run_wrapped_command(command_str=command_str)
299
+
300
+ def swarm_adversarial(self, task_prompt: str, language: str = "python") -> Any:
301
+ """Feature 7: Adversarial Red Team / Blue Team Consensus Loop."""
302
+ from k_cli.agents.adversarial_swarm import AdversarialConsensusSwarm
303
+ swarm = AdversarialConsensusSwarm(llm_driver=self.driver, verifier=self.verifier)
304
+ return swarm.run_consensus(task_prompt=task_prompt, language=language)
305
+
306
+ def synapse(self, query: str) -> Any:
307
+ """Feature 8: AST Neural Code Graph & Context Compressor."""
308
+ from k_cli.tools.synapse_graph import SynapseCodeGraph
309
+ graph = SynapseCodeGraph(repo_path=str(self.repo_path))
310
+ return graph.extract_subgraph_slice(query=query)
311
+
312
+ def airgap(self) -> Any:
313
+ """Feature 9: Sovereign Air-Gapped Offline Engine."""
314
+ from k_cli.core.airgap import AirgapManager
315
+ mgr = AirgapManager()
316
+ return mgr.audit_environment()
317
+
318
+ def scaffold(self, spec_prompt: str, target_dir: str = "./scaffolded_app", write_to_disk: bool = False) -> Any:
319
+ """Feature 10: Natural Language Full-Stack Scaffolder."""
320
+ from k_cli.agents.scaffold_engine import FullStackScaffolder
321
+ scaffolder = FullStackScaffolder(llm_driver=self.driver, verifier=self.verifier)
322
+ return scaffolder.scaffold(spec_prompt=spec_prompt, target_dir=target_dir, write_to_disk=write_to_disk)