kernelport 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kernelport/__init__.py +3 -0
- kernelport/__main__.py +5 -0
- kernelport/_skills/kernelport/SKILL.md +200 -0
- kernelport/_skills/kernelport/backends/cpu.md +138 -0
- kernelport/_skills/kernelport/backends/hip.md +53 -0
- kernelport/_skills/kernelport/backends/metal.md +76 -0
- kernelport/_skills/kernelport/backends/triton.md +117 -0
- kernelport/_skills/kernelport/backends/webgpu.md +146 -0
- kernelport/_skills/kernelport/common_bugs.md +40 -0
- kernelport/agent.py +178 -0
- kernelport/analyzer/__init__.py +0 -0
- kernelport/analyzer/cuda_parser.py +480 -0
- kernelport/analyzer/models.py +80 -0
- kernelport/analyzer/suggest.py +120 -0
- kernelport/backends/__init__.py +5 -0
- kernelport/backends/base.py +138 -0
- kernelport/backends/cpu/__init__.py +1 -0
- kernelport/backends/cpu/capability.py +25 -0
- kernelport/backends/cpu/config.py +36 -0
- kernelport/backends/cpu/runner.py +67 -0
- kernelport/backends/hip/__init__.py +1 -0
- kernelport/backends/hip/capability.py +34 -0
- kernelport/backends/hip/config.py +28 -0
- kernelport/backends/hip/runner.py +48 -0
- kernelport/backends/metal/__init__.py +1 -0
- kernelport/backends/metal/capability.py +32 -0
- kernelport/backends/metal/config.py +35 -0
- kernelport/backends/metal/runner.py +142 -0
- kernelport/backends/triton/__init__.py +1 -0
- kernelport/backends/triton/capability.py +29 -0
- kernelport/backends/triton/config.py +41 -0
- kernelport/backends/triton/runner.py +44 -0
- kernelport/backends/webgpu/__init__.py +1 -0
- kernelport/backends/webgpu/capability.py +34 -0
- kernelport/backends/webgpu/config.py +38 -0
- kernelport/backends/webgpu/runner.py +285 -0
- kernelport/bench/__init__.py +0 -0
- kernelport/bench/timer.py +76 -0
- kernelport/cli.py +501 -0
- kernelport/doctor.py +285 -0
- kernelport/hardware.py +60 -0
- kernelport/harness/__init__.py +0 -0
- kernelport/harness/compare.py +152 -0
- kernelport/harness/device_source.py +273 -0
- kernelport/harness/expr.py +80 -0
- kernelport/harness/inputs.py +194 -0
- kernelport/harness/reference.py +76 -0
- kernelport/harness/results.py +118 -0
- kernelport/harness/run_cuda.py +126 -0
- kernelport/harness/spec.py +199 -0
- kernelport/harness/tolerances.py +48 -0
- kernelport/harness/verify.py +131 -0
- kernelport/hashing.py +28 -0
- kernelport/mcp_server.py +95 -0
- kernelport/report/__init__.py +1 -0
- kernelport/report/data.py +147 -0
- kernelport/report/html.py +174 -0
- kernelport/report/markdown.py +75 -0
- kernelport/setup_agents/__init__.py +1 -0
- kernelport/setup_agents/backup.py +59 -0
- kernelport/setup_agents/detect.py +78 -0
- kernelport/setup_agents/register.py +302 -0
- kernelport/setup_agents/skills_install.py +31 -0
- kernelport/tools.py +455 -0
- kernelport/tune.py +99 -0
- kernelport/workspace.py +400 -0
- kernelport/zoo.py +176 -0
- kernelport-0.1.0.dist-info/METADATA +228 -0
- kernelport-0.1.0.dist-info/RECORD +72 -0
- kernelport-0.1.0.dist-info/WHEEL +4 -0
- kernelport-0.1.0.dist-info/entry_points.txt +2 -0
- kernelport-0.1.0.dist-info/licenses/LICENSE +21 -0
kernelport/cli.py
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
"""kernelport command line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
app = typer.Typer(help="Port CUDA kernels to other backends and prove they are correct.",
|
|
10
|
+
no_args_is_help=True)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@app.callback()
|
|
14
|
+
def main() -> None:
|
|
15
|
+
"""kernelport: your agent writes the port, kernelport runs it and proves it."""
|
|
16
|
+
_safe_streams()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _safe_streams() -> None:
|
|
20
|
+
"""Never crash on characters like → or ± (Windows cp1252 consoles).
|
|
21
|
+
|
|
22
|
+
Piped output (agents, CI) becomes UTF-8; a real console keeps its encoding and shows
|
|
23
|
+
"?" for what it cannot display.
|
|
24
|
+
"""
|
|
25
|
+
import sys
|
|
26
|
+
|
|
27
|
+
for stream in (sys.stdout, sys.stderr):
|
|
28
|
+
enc = (getattr(stream, "encoding", None) or "").lower().replace("-", "")
|
|
29
|
+
if enc == "utf8" or not hasattr(stream, "reconfigure"):
|
|
30
|
+
continue
|
|
31
|
+
if stream.isatty():
|
|
32
|
+
stream.reconfigure(errors="replace")
|
|
33
|
+
else:
|
|
34
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _console():
|
|
38
|
+
"""Rich console; piped output gets 160 columns instead of Rich's default 80."""
|
|
39
|
+
import sys
|
|
40
|
+
|
|
41
|
+
from rich.console import Console
|
|
42
|
+
|
|
43
|
+
return Console() if sys.stdout.isatty() else Console(width=160)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@app.command()
|
|
47
|
+
def doctor(as_json: bool = typer.Option(False, "--json", help="Print JSON instead of a table.")) -> None:
|
|
48
|
+
"""Show environment info and smoke-test every available backend (MCP: kernelport_doctor)."""
|
|
49
|
+
from kernelport.doctor import print_report, run_doctor
|
|
50
|
+
|
|
51
|
+
report = run_doctor()
|
|
52
|
+
if as_json:
|
|
53
|
+
print(json.dumps(report.to_dict(), indent=2))
|
|
54
|
+
else:
|
|
55
|
+
print_report(report)
|
|
56
|
+
raise typer.Exit(0 if report.ok else 1)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@app.command()
|
|
60
|
+
def zoo(
|
|
61
|
+
backend: str = typer.Option("triton", help="Port backend to verify."),
|
|
62
|
+
kernel: list[str] = typer.Option(None, "--kernel", "-k", help="Only these kernels."),
|
|
63
|
+
no_bench: bool = typer.Option(False, "--no-bench", help="Skip benchmarking."),
|
|
64
|
+
) -> None:
|
|
65
|
+
"""Validate zoo originals, verify stored ports, and benchmark passing ports."""
|
|
66
|
+
from pathlib import Path
|
|
67
|
+
|
|
68
|
+
from rich.markup import escape
|
|
69
|
+
from rich.table import Table
|
|
70
|
+
|
|
71
|
+
from kernelport.zoo import find_zoo, run_zoo
|
|
72
|
+
|
|
73
|
+
con = _console()
|
|
74
|
+
entries = run_zoo(find_zoo(), kernel or None, (backend,), bench=not no_bench,
|
|
75
|
+
out_dir=Path(".kernelport") / "zoo")
|
|
76
|
+
colors = {"PASS": "green", "FAIL": "red", "UNVERIFIED": "yellow", "SKIPPED": "dim"}
|
|
77
|
+
table = Table(title=f"zoo: original vs reference, {backend} port vs reference")
|
|
78
|
+
for col in ("kernel", "original", "cases", backend, "cases", "orig ms", "port ms", "speedup"):
|
|
79
|
+
table.add_column(col)
|
|
80
|
+
for e in entries:
|
|
81
|
+
p = e.ports[backend]
|
|
82
|
+
b = e.bench.get(backend)
|
|
83
|
+
table.add_row(
|
|
84
|
+
e.kernel,
|
|
85
|
+
f"[{colors[e.original.status]}]{e.original.status}[/]",
|
|
86
|
+
f"{e.original.num_passed}/{len(e.original.cases)}",
|
|
87
|
+
f"[{colors[p.status]}]{p.status}[/]",
|
|
88
|
+
f"{p.num_passed}/{len(p.cases)}" if p.cases else escape(p.reason),
|
|
89
|
+
f"{b['original_ms']:.4f}" if b and b["original_ms"] is not None else "-",
|
|
90
|
+
f"{b['port_ms']:.4f}" if b else "-",
|
|
91
|
+
(f"{b['speedup']:.2f}x" + ("" if b["comparable"] else " [dim](n/c)[/]"))
|
|
92
|
+
if b and b["speedup"] is not None else "-",
|
|
93
|
+
)
|
|
94
|
+
con.print(table)
|
|
95
|
+
notes = {b["note"] for e in entries for b in e.bench.values() if not b["comparable"]}
|
|
96
|
+
for note in notes:
|
|
97
|
+
con.print(f"[dim](n/c) not comparable: {escape(note)}[/]")
|
|
98
|
+
for e in entries:
|
|
99
|
+
for r in [e.original, *e.ports.values()]:
|
|
100
|
+
if r.status == "FAIL":
|
|
101
|
+
con.print(escape(r.failure_report()))
|
|
102
|
+
failed = any(e.original.status == "FAIL" or any(r.status == "FAIL" for r in e.ports.values())
|
|
103
|
+
for e in entries)
|
|
104
|
+
raise typer.Exit(1 if failed else 0)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _emit(result: dict, as_json: bool, extra_keys: tuple[str, ...] = ("report",)) -> None:
|
|
108
|
+
"""Print a tool result: JSON, or summary plus any report text."""
|
|
109
|
+
from rich.markup import escape
|
|
110
|
+
|
|
111
|
+
if as_json:
|
|
112
|
+
print(json.dumps(result, indent=2, default=str))
|
|
113
|
+
else:
|
|
114
|
+
con = _console()
|
|
115
|
+
color = "green" if result.get("ok") else "red"
|
|
116
|
+
con.print(f"[{color}]{escape(result.get('summary', ''))}[/]")
|
|
117
|
+
for k in extra_keys:
|
|
118
|
+
if result.get(k):
|
|
119
|
+
con.print(escape(str(result[k])))
|
|
120
|
+
if not result.get("ok", False):
|
|
121
|
+
raise typer.Exit(1)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
JSON_OPT = typer.Option(False, "--json", help="Print the full JSON result.")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@app.command()
|
|
128
|
+
def scan(path: str = typer.Argument(".", help="File or directory inside this repo."), as_json: bool = JSON_OPT) -> None:
|
|
129
|
+
"""Find CUDA kernels and register them in .kernelport/ (MCP: scan_kernels)."""
|
|
130
|
+
from rich.markup import escape
|
|
131
|
+
from rich.table import Table
|
|
132
|
+
|
|
133
|
+
from kernelport import tools
|
|
134
|
+
|
|
135
|
+
res = tools.scan_kernels(path)
|
|
136
|
+
if as_json or not res.get("ok"):
|
|
137
|
+
_emit(res, as_json)
|
|
138
|
+
return
|
|
139
|
+
table = Table(title=res["summary"])
|
|
140
|
+
table.add_column("kernel id", no_wrap=True)
|
|
141
|
+
for col in ("line", "params", "features"):
|
|
142
|
+
table.add_column(col)
|
|
143
|
+
for k in res["kernels"]:
|
|
144
|
+
table.add_row(escape(k["kernel_id"]), str(k["line"]), escape(", ".join(k["params"])), ", ".join(k["features"]))
|
|
145
|
+
_console().print(table)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@app.command()
|
|
149
|
+
def read(kernel_id: str, as_json: bool = JSON_OPT) -> None:
|
|
150
|
+
"""Show a kernel's source, signature and input spec (MCP: read_kernel)."""
|
|
151
|
+
from kernelport import tools
|
|
152
|
+
|
|
153
|
+
res = tools.read_kernel(kernel_id)
|
|
154
|
+
if not as_json and res.get("ok"):
|
|
155
|
+
print(res["source"])
|
|
156
|
+
print(json.dumps(res["input_spec"], indent=2))
|
|
157
|
+
_emit(res, as_json, ())
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@app.command()
|
|
161
|
+
def skill(name: str = typer.Argument("workflow")) -> None:
|
|
162
|
+
"""Print a skill file (MCP: read_skill)."""
|
|
163
|
+
from kernelport import tools
|
|
164
|
+
|
|
165
|
+
res = tools.read_skill(name)
|
|
166
|
+
if res.get("ok"):
|
|
167
|
+
print(res["content"])
|
|
168
|
+
else:
|
|
169
|
+
_emit(res, False)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@app.command("write-reference")
|
|
173
|
+
def write_reference_cmd(kernel_id: str, file: str, spec: str = typer.Option(None, help="launch.json to save too."),
|
|
174
|
+
as_json: bool = JSON_OPT) -> None:
|
|
175
|
+
"""Save a candidate reference from a file (MCP: write_reference)."""
|
|
176
|
+
from pathlib import Path
|
|
177
|
+
|
|
178
|
+
from kernelport import tools
|
|
179
|
+
|
|
180
|
+
spec_obj = json.loads(Path(spec).read_text(encoding="utf-8")) if spec else None
|
|
181
|
+
_emit(tools.write_reference(kernel_id, Path(file).read_text(encoding="utf-8"), spec_obj), as_json)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@app.command()
|
|
185
|
+
def validate(kernel_id: str = typer.Argument(None),
|
|
186
|
+
all_: bool = typer.Option(False, "--all",
|
|
187
|
+
help="Every kernel whose candidate reference is not frozen yet."),
|
|
188
|
+
as_json: bool = JSON_OPT) -> None:
|
|
189
|
+
"""Run the original CUDA kernel against the reference; freeze on PASS (MCP: validate_reference)."""
|
|
190
|
+
from rich.markup import escape
|
|
191
|
+
|
|
192
|
+
from kernelport import tools
|
|
193
|
+
from kernelport.workspace import Workspace
|
|
194
|
+
|
|
195
|
+
if bool(kernel_id) == all_:
|
|
196
|
+
raise typer.BadParameter("give a kernel id or --all (not both)")
|
|
197
|
+
if kernel_id:
|
|
198
|
+
_emit(tools.validate_reference(kernel_id), as_json)
|
|
199
|
+
return
|
|
200
|
+
ws = Workspace()
|
|
201
|
+
ids = ws.pending_validation() if ws.dir.is_dir() else []
|
|
202
|
+
results = []
|
|
203
|
+
for kid in ids:
|
|
204
|
+
r = {"kernel_id": kid, **tools.validate_reference(kid)}
|
|
205
|
+
results.append(r)
|
|
206
|
+
if r.get("status") == "UNAVAILABLE":
|
|
207
|
+
break # same reason for every kernel
|
|
208
|
+
if as_json:
|
|
209
|
+
print(json.dumps(results, indent=2, default=str))
|
|
210
|
+
else:
|
|
211
|
+
con = _console()
|
|
212
|
+
if not ids:
|
|
213
|
+
con.print("nothing to validate: every candidate reference is already frozen")
|
|
214
|
+
for r in results:
|
|
215
|
+
color = "green" if r.get("ok") else "red"
|
|
216
|
+
con.print(f"[{color}]{escape(r['kernel_id'])}: {escape(r.get('summary', ''))}[/]")
|
|
217
|
+
if r.get("report"):
|
|
218
|
+
con.print(escape(r["report"]))
|
|
219
|
+
if any(not r.get("ok") for r in results):
|
|
220
|
+
raise typer.Exit(1)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
@app.command("write-port")
|
|
224
|
+
def write_port_cmd(kernel_id: str, backend: str, file: str, as_json: bool = JSON_OPT) -> None:
|
|
225
|
+
"""Save a port from a file (MCP: write_port)."""
|
|
226
|
+
from pathlib import Path
|
|
227
|
+
|
|
228
|
+
from kernelport import tools
|
|
229
|
+
|
|
230
|
+
_emit(tools.write_port(kernel_id, backend, Path(file).read_text(encoding="utf-8")), as_json)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _saved_ports(backend: str | None, kernel: str | None) -> list[tuple[str, str]]:
|
|
234
|
+
from kernelport.backends.base import BACKEND_NAMES
|
|
235
|
+
from kernelport.workspace import Workspace
|
|
236
|
+
|
|
237
|
+
ws = Workspace()
|
|
238
|
+
pairs = []
|
|
239
|
+
ids = [ws.get(kernel).id] if kernel else ws.kernel_ids() if ws.dir.is_dir() else []
|
|
240
|
+
for kid in ids:
|
|
241
|
+
for b in ([backend] if backend else BACKEND_NAMES):
|
|
242
|
+
if ws.port_path(kid, b).is_file():
|
|
243
|
+
pairs.append((kid, b))
|
|
244
|
+
return pairs
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
@app.command()
|
|
248
|
+
def verify(backend: str = typer.Option(None, help="Only this backend."),
|
|
249
|
+
kernel: str = typer.Option(None, help="Only this kernel id."),
|
|
250
|
+
as_json: bool = JSON_OPT) -> None:
|
|
251
|
+
"""Verify saved ports in .kernelport/ on this machine (MCP: verify_port)."""
|
|
252
|
+
from rich.markup import escape
|
|
253
|
+
|
|
254
|
+
from kernelport import tools
|
|
255
|
+
|
|
256
|
+
pairs = _saved_ports(backend, kernel)
|
|
257
|
+
results = [{"kernel_id": k, "backend": b, **tools.verify_port(k, b)} for k, b in pairs]
|
|
258
|
+
if as_json:
|
|
259
|
+
print(json.dumps(results, indent=2, default=str))
|
|
260
|
+
else:
|
|
261
|
+
con = _console()
|
|
262
|
+
if not pairs:
|
|
263
|
+
con.print("no saved ports to verify")
|
|
264
|
+
for r in results:
|
|
265
|
+
color = {"PASS": "green", "FAIL": "red"}.get(r.get("status"), "yellow")
|
|
266
|
+
con.print(f"[{color}]{escape(r['kernel_id'])} / {r['backend']}: {escape(r['summary'])}[/]")
|
|
267
|
+
if r.get("report"):
|
|
268
|
+
con.print(escape(r["report"]))
|
|
269
|
+
if any(r.get("status") == "FAIL" or r.get("status") == "REFUSED" for r in results):
|
|
270
|
+
raise typer.Exit(1)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
@app.command()
|
|
274
|
+
def bench(backend: str = typer.Option(None, help="Only this backend."),
|
|
275
|
+
kernel: str = typer.Option(None, help="Only this kernel id."),
|
|
276
|
+
dtype: str = typer.Option(None, help="Default: float32, or the spec's first dtype."),
|
|
277
|
+
as_json: bool = JSON_OPT) -> None:
|
|
278
|
+
"""Benchmark saved ports that passed on this machine (MCP: bench_port)."""
|
|
279
|
+
from rich.markup import escape
|
|
280
|
+
|
|
281
|
+
from kernelport import tools
|
|
282
|
+
|
|
283
|
+
results = [{"kernel_id": k, "backend": b, **tools.bench_port(k, b, {"dtype": dtype})}
|
|
284
|
+
for k, b in _saved_ports(backend, kernel)]
|
|
285
|
+
if as_json:
|
|
286
|
+
print(json.dumps(results, indent=2, default=str))
|
|
287
|
+
return
|
|
288
|
+
for r in results:
|
|
289
|
+
_console().print(f"{escape(r['kernel_id'])} / {r['backend']}: {escape(r['summary'])}")
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
@app.command()
|
|
293
|
+
def tune(kernel_id: str, backend: str,
|
|
294
|
+
dtype: str = typer.Option(None, help="Default: float32, or the spec's first dtype."),
|
|
295
|
+
as_json: bool = JSON_OPT) -> None:
|
|
296
|
+
"""Try the port's TUNE combinations, keep the fastest that passes (MCP: tune_port)."""
|
|
297
|
+
from rich.markup import escape
|
|
298
|
+
from rich.table import Table
|
|
299
|
+
|
|
300
|
+
from kernelport import tools
|
|
301
|
+
|
|
302
|
+
result = tools.tune_port(kernel_id, backend, dtype)
|
|
303
|
+
if not as_json and result.get("rows"):
|
|
304
|
+
table = Table(title=f"tune {kernel_id} / {backend} ({result.get('dtype') or dtype})")
|
|
305
|
+
for col in ("params", "status", "cases", "port ms", ""):
|
|
306
|
+
table.add_column(col)
|
|
307
|
+
for r in result["rows"]:
|
|
308
|
+
table.add_row(escape(json.dumps(r["params"])), r["status"], f"{r['cases_passed']}/{r['cases_total']}",
|
|
309
|
+
f"{r['port_ms']:.4f}" if r["port_ms"] is not None else "-",
|
|
310
|
+
"current" if r["current"] else ("best" if r["params"] == result.get("best") else ""))
|
|
311
|
+
_console().print(table)
|
|
312
|
+
_emit(result, as_json)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
@app.command()
|
|
316
|
+
def status(show_all: bool = typer.Option(False, "--all", help="Also list kernels with no reference or port."),
|
|
317
|
+
as_json: bool = JSON_OPT) -> None:
|
|
318
|
+
"""Kernel x backend x hardware status table (MCP: list_status)."""
|
|
319
|
+
import sys
|
|
320
|
+
|
|
321
|
+
from rich.markup import escape
|
|
322
|
+
from rich.table import Table
|
|
323
|
+
|
|
324
|
+
from kernelport import tools
|
|
325
|
+
|
|
326
|
+
res = tools.list_status()
|
|
327
|
+
if as_json:
|
|
328
|
+
print(json.dumps(res, indent=2))
|
|
329
|
+
return
|
|
330
|
+
rows = res["rows"]
|
|
331
|
+
idle = [r for r in rows if r["backend"] == "-" and r["reference"] != "frozen"]
|
|
332
|
+
if not show_all:
|
|
333
|
+
rows = [r for r in rows if r not in idle]
|
|
334
|
+
colors = {"PASS": "green", "FAIL": "red", "UNVERIFIED": "yellow", "SKIPPED": "dim"}
|
|
335
|
+
table = Table(title=res["summary"])
|
|
336
|
+
table.add_column("kernel", no_wrap=True)
|
|
337
|
+
for col in ("reference", "backend", "hardware", "status", "cases"):
|
|
338
|
+
table.add_column(col)
|
|
339
|
+
table.add_column("reason", overflow="fold")
|
|
340
|
+
for r in rows:
|
|
341
|
+
table.add_row(escape(r["kernel"].split("::")[-1]), r["reference"], r["backend"], escape(r["hardware"]),
|
|
342
|
+
f"[{colors[r['status']]}]{r['status']}[/]", r["cases"], escape(r["reason"]))
|
|
343
|
+
# Piped output (agents, CI logs) gets a readable width instead of Rich's 80 columns.
|
|
344
|
+
con = _console()
|
|
345
|
+
con.print(table)
|
|
346
|
+
if idle and not show_all:
|
|
347
|
+
con.print(f"[dim]{len(idle)} more kernels have no reference or port yet (--all lists them)[/]")
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
@app.command()
|
|
351
|
+
def report(markdown: bool = typer.Option(False, "--markdown", "--md", help="Write report.md and print it."),
|
|
352
|
+
as_json: bool = JSON_OPT) -> None:
|
|
353
|
+
"""Build the HTML (or Markdown) report (MCP: make_report)."""
|
|
354
|
+
from kernelport import tools
|
|
355
|
+
|
|
356
|
+
res = tools.make_report("markdown" if markdown else "html")
|
|
357
|
+
if markdown and not as_json and res.get("ok"):
|
|
358
|
+
print(res["content"])
|
|
359
|
+
return
|
|
360
|
+
_emit(res, as_json)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
TRY_PROMPT = 'port the CUDA kernels in this repo to Triton and verify them'
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
@app.command()
|
|
367
|
+
def setup(
|
|
368
|
+
uninstall: bool = typer.Option(False, "--uninstall", help="Undo everything a previous setup added."),
|
|
369
|
+
print_only: bool = typer.Option(False, "--print", help="Only print manual instructions; change nothing."),
|
|
370
|
+
agent: list[str] = typer.Option(None, "--agent", "-a", help="Only these agents: claude, codex, cursor, gemini."),
|
|
371
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Apply without asking (still shows the changes)."),
|
|
372
|
+
home: str = typer.Option(None, "--home", hidden=True, help="Home directory override (tests)."),
|
|
373
|
+
no_cli: bool = typer.Option(False, "--no-agent-cli", hidden=True, help="Edit config files instead of `claude mcp add`."),
|
|
374
|
+
) -> None:
|
|
375
|
+
"""Register the kernelport MCP server and skill with your coding agents."""
|
|
376
|
+
from pathlib import Path
|
|
377
|
+
|
|
378
|
+
from rich.markup import escape
|
|
379
|
+
from rich.table import Table
|
|
380
|
+
|
|
381
|
+
from kernelport.setup_agents.detect import agents as all_agents
|
|
382
|
+
from kernelport.setup_agents.detect import server_command
|
|
383
|
+
from kernelport.setup_agents.register import SetupError, apply, plan, plan_uninstall
|
|
384
|
+
from kernelport.setup_agents.register import uninstall as do_uninstall
|
|
385
|
+
|
|
386
|
+
con = _console()
|
|
387
|
+
home_p = Path(home) if home else Path.home()
|
|
388
|
+
|
|
389
|
+
if uninstall:
|
|
390
|
+
changes = plan_uninstall(home_p)
|
|
391
|
+
if not changes:
|
|
392
|
+
con.print("nothing to uninstall: kernelport setup has not changed any agent config")
|
|
393
|
+
return
|
|
394
|
+
for c in changes:
|
|
395
|
+
con.print(f"- {c.agent}: {escape(c.preview)} ({escape(str(c.path))})")
|
|
396
|
+
if not yes and not typer.confirm("Undo these changes?", default=False):
|
|
397
|
+
raise typer.Exit(1)
|
|
398
|
+
dest = do_uninstall(home_p)
|
|
399
|
+
con.print(f"[green]done.[/] Current files were backed up to {escape(str(dest))}. Restart your agents.")
|
|
400
|
+
return
|
|
401
|
+
|
|
402
|
+
found = all_agents(home_p, check_path=not home)
|
|
403
|
+
chosen = [a for a in found if (a.key in agent if agent else a.detected)]
|
|
404
|
+
if agent:
|
|
405
|
+
unknown = set(agent) - {a.key for a in found}
|
|
406
|
+
if unknown:
|
|
407
|
+
con.print(f"[red]unknown agent(s): {', '.join(sorted(unknown))}[/]")
|
|
408
|
+
raise typer.Exit(2)
|
|
409
|
+
|
|
410
|
+
table = Table(title="coding agents")
|
|
411
|
+
for col in ("agent", "detected", "MCP config", "skill folder"):
|
|
412
|
+
table.add_column(col)
|
|
413
|
+
for a in found:
|
|
414
|
+
table.add_row(a.label, "yes" if a.detected else "no", escape(str(a.config_path)), escape(str(a.skill_dir)))
|
|
415
|
+
con.print(table)
|
|
416
|
+
|
|
417
|
+
command = server_command()
|
|
418
|
+
if print_only:
|
|
419
|
+
con.print("\n[bold]Manual setup[/] (nothing was changed):")
|
|
420
|
+
con.print(f"MCP server command: {escape(' '.join(command))}")
|
|
421
|
+
for c in plan(found, command, use_cli=False):
|
|
422
|
+
con.print(f"\n[bold]{c.agent}[/] {c.kind}: {escape(str(c.path))}\n{escape(c.preview)}")
|
|
423
|
+
return
|
|
424
|
+
if not chosen:
|
|
425
|
+
con.print("No supported agents detected. Use --agent to pick one, or --print for manual steps.")
|
|
426
|
+
raise typer.Exit(1)
|
|
427
|
+
|
|
428
|
+
try:
|
|
429
|
+
changes = plan(chosen, command, use_cli=not no_cli)
|
|
430
|
+
except SetupError as exc:
|
|
431
|
+
con.print(f"[red]{escape(str(exc))}[/]")
|
|
432
|
+
raise typer.Exit(1)
|
|
433
|
+
con.print("\n[bold]Planned changes[/] (every touched file is backed up first):")
|
|
434
|
+
for c in changes:
|
|
435
|
+
con.print(f"\n[bold]{c.agent}[/] {c.kind} [{c.action}] {escape(str(c.path))}"
|
|
436
|
+
+ (" via the agent's own CLI" if c.method == "cli" else ""))
|
|
437
|
+
if c.action != "unchanged":
|
|
438
|
+
con.print(escape(c.preview))
|
|
439
|
+
if all(c.action == "unchanged" for c in changes):
|
|
440
|
+
con.print("\nEverything is already set up.")
|
|
441
|
+
return
|
|
442
|
+
if not yes and not typer.confirm("\nApply these changes?", default=False):
|
|
443
|
+
con.print("No changes made.")
|
|
444
|
+
raise typer.Exit(1)
|
|
445
|
+
try:
|
|
446
|
+
dest = apply(changes, home_p)
|
|
447
|
+
except SetupError as exc:
|
|
448
|
+
con.print(f"[red]{escape(str(exc))}[/]")
|
|
449
|
+
raise typer.Exit(1)
|
|
450
|
+
con.print(f"\n[green]Done.[/] Backups: {escape(str(dest))}")
|
|
451
|
+
con.print(f'Restart your agent, then try: "{TRY_PROMPT}"')
|
|
452
|
+
con.print("Undo with: kernelport setup --uninstall")
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
@app.command()
|
|
456
|
+
def agent(
|
|
457
|
+
task: str = typer.Argument(TRY_PROMPT, help="What to do, in plain words."),
|
|
458
|
+
model: str = typer.Option(None, help="Claude model id (default: claude-opus-5-5)."),
|
|
459
|
+
effort: str = typer.Option("high", help="low | medium | high | xhigh | max"),
|
|
460
|
+
max_turns: int = typer.Option(80, help="Stop after this many model turns."),
|
|
461
|
+
no_fallbacks: bool = typer.Option(False, "--no-fallbacks", help="Disable server-side refusal fallbacks."),
|
|
462
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Start without the cost confirmation."),
|
|
463
|
+
) -> None:
|
|
464
|
+
"""Built-in agent (optional): Claude drives the kernelport tools via YOUR Anthropic API key.
|
|
465
|
+
|
|
466
|
+
For people without a coding agent. Needs `pip install kernelport[agent]` and ANTHROPIC_API_KEY
|
|
467
|
+
(or an `ant auth login` profile). Every run is billed to that account.
|
|
468
|
+
"""
|
|
469
|
+
from rich.markup import escape
|
|
470
|
+
|
|
471
|
+
from kernelport import agent as kp_agent
|
|
472
|
+
from kernelport.workspace import find_root
|
|
473
|
+
|
|
474
|
+
con = _console()
|
|
475
|
+
root = find_root()
|
|
476
|
+
model = model or kp_agent.DEFAULT_MODEL
|
|
477
|
+
con.print(f"repo: {escape(str(root))}\nmodel: {model} (effort {effort}), up to {max_turns} turns\n"
|
|
478
|
+
"This uses the Anthropic API and is billed to your account.")
|
|
479
|
+
if not yes and not typer.confirm("Start?", default=False):
|
|
480
|
+
raise typer.Exit(1)
|
|
481
|
+
try:
|
|
482
|
+
res = kp_agent.run_agent(task, root, model=model, effort=effort, max_turns=max_turns,
|
|
483
|
+
fallbacks=not no_fallbacks, on_event=lambda s: con.print(escape(s)))
|
|
484
|
+
except RuntimeError as exc:
|
|
485
|
+
con.print(f"[red]{escape(str(exc))}[/]")
|
|
486
|
+
raise typer.Exit(2)
|
|
487
|
+
con.print(f"\n[dim]stop: {res.stop_reason}; {res.turns} turns, {res.tool_calls} tool calls; tokens in "
|
|
488
|
+
f"{res.input_tokens} (cache read {res.cache_read_tokens}), out {res.output_tokens}[/]")
|
|
489
|
+
raise typer.Exit(0 if res.stop_reason == "end_turn" else 1)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
@app.command()
|
|
493
|
+
def mcp() -> None:
|
|
494
|
+
"""Start the MCP server on stdio (used by agent configs)."""
|
|
495
|
+
from kernelport.mcp_server import main as serve
|
|
496
|
+
|
|
497
|
+
serve()
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
if __name__ == "__main__":
|
|
501
|
+
app()
|