wgpu-shift 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.
gpu_shift/cli.py ADDED
@@ -0,0 +1,609 @@
1
+ """CLI entrypoint for gpu-shift."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import dataclasses
7
+ import json
8
+ import math
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from gpu_shift import __version__
14
+ from gpu_shift.bench import bench_unit
15
+ from gpu_shift.capture import capture_unit
16
+ from gpu_shift.check import check_unit
17
+ from gpu_shift.demo import run_demo
18
+ from gpu_shift.device import list_adapters, run_smoke_test
19
+ from gpu_shift.diff import diff_unit
20
+ from gpu_shift.mcp_server import serve_stdio
21
+ from gpu_shift.report import generate_report
22
+ from gpu_shift.run import run_workflow
23
+ from gpu_shift.scan import scan_command
24
+ from gpu_shift.setup import SUPPORTED_AGENTS, setup_agents
25
+ from gpu_shift.stage import create_stage
26
+ from gpu_shift.switch import disable_unit, enable_unit
27
+
28
+
29
+ def _to_jsonable(obj: Any) -> Any:
30
+ if isinstance(obj, Path):
31
+ return obj.as_posix()
32
+ if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
33
+ return {k: _to_jsonable(v) for k, v in dataclasses.asdict(obj).items()}
34
+ if isinstance(obj, dict):
35
+ return {str(k): _to_jsonable(v) for k, v in obj.items()}
36
+ if isinstance(obj, (list, tuple)):
37
+ return [_to_jsonable(v) for v in obj]
38
+ if isinstance(obj, float):
39
+ if math.isnan(obj):
40
+ return "nan"
41
+ if math.isinf(obj):
42
+ return "inf" if obj > 0 else "-inf"
43
+ return obj
44
+
45
+
46
+ def _print_json(payload: Any) -> None:
47
+ print(json.dumps(_to_jsonable(payload), indent=2))
48
+
49
+
50
+ def _cmd_doctor(args: argparse.Namespace) -> int:
51
+ adapters = list_adapters()
52
+ if not adapters:
53
+ if args.json:
54
+ _print_json({"adapters": [], "passed": False, "error": "No WebGPU adapters detected"})
55
+ else:
56
+ print("No WebGPU adapters detected.")
57
+ return 1
58
+
59
+ result = run_smoke_test(power_preference=args.power_preference)
60
+ if args.json:
61
+ _print_json({"version": __version__, "adapters": adapters, "smoke": result})
62
+ return 0 if result["passed"] else 1
63
+
64
+ print(f"gpu-shift {__version__}")
65
+ print(f"Detected WebGPU adapters ({len(adapters)}):")
66
+ for idx, info in enumerate(adapters):
67
+ kind_tag = "" if info.is_hardware else " [software emulator - CI/test only]"
68
+ print(
69
+ f" [{idx}] {info.device} "
70
+ f"(type={info.adapter_type}, backend={info.backend_type}, vendor={info.vendor}){kind_tag}"
71
+ )
72
+ selected = result["adapter"]
73
+ status = "PASS" if result["passed"] else "FAIL"
74
+ print(
75
+ f"Selected adapter: {selected.device} "
76
+ f"({selected.adapter_type}, {selected.backend_type})"
77
+ )
78
+ print(
79
+ f"WGSL compute smoke test: {status} "
80
+ f"(n={result['size']}, max_abs_err={result['max_abs_err']:.2e}, "
81
+ f"time={result['elapsed_ms']:.2f} ms)"
82
+ )
83
+ return 0 if result["passed"] else 1
84
+
85
+
86
+ def _cmd_demo(args: argparse.Namespace) -> int:
87
+ res = run_demo(power_preference=args.power_preference)
88
+ if args.json:
89
+ _print_json(res)
90
+ return 0 if (res.diff_passed == res.diff_total and res.vram_clean) else 1
91
+
92
+ print(f"gpu-shift {__version__} live demo (2D bilateral image filter)")
93
+ print(f"GPU: {res.adapter.device} ({res.adapter.adapter_type}, {res.adapter.backend_type})")
94
+ print(
95
+ f"Diff: {res.diff_passed}/{res.diff_total} PASS "
96
+ f"(incl. 1x1, 17x13 prime, non-contiguous; max_abs_err={res.max_abs_err:.2e})"
97
+ )
98
+ vram_status = "PASS" if res.vram_clean else "FAIL"
99
+ print(f"VRAM: {vram_status} (15-dispatch soak delta={res.vram_delta_bytes} B)")
100
+ print("End-to-end crossover sweep (CPU vectorized NumPy vs WebGPU/WGSL, transfers included):")
101
+ print(f" {'Shape':<10} {'Elements':>10} {'CPU (ms)':>10} {'GPU (ms)':>10} {'Speedup':>9}")
102
+ for pt in res.sweep_points:
103
+ print(
104
+ f" {pt.label:<10} {pt.elements:>10,} "
105
+ f"{pt.cpu_ms:>10.2f} {pt.gpu_ms:>10.2f} {pt.speedup:>8.2f}x"
106
+ )
107
+ print(f"Verdict: {res.verdict}")
108
+ return 0 if (res.diff_passed == res.diff_total and res.vram_clean) else 1
109
+
110
+
111
+ def _cmd_scan(args: argparse.Namespace) -> int:
112
+ res = scan_command(
113
+ cmd=list(args.cmd),
114
+ project_root=Path(args.root) if args.root else None,
115
+ top_k=args.top,
116
+ )
117
+ if args.json:
118
+ _print_json(res)
119
+ return 0
120
+
121
+ print(f"SCAN (total {res.total_ms:.2f} ms, root={res.project_root.as_posix()})")
122
+ if not res.candidates:
123
+ print(" No user-code candidates detected.")
124
+ return 0
125
+ print(f" {'Score':>5} {'Cum (ms)':>10} {'Share':>7} {'Calls':>7} Function")
126
+ for cand in res.candidates:
127
+ flag = "" if cand.stageable else " [skip]"
128
+ reasons = ", ".join(cand.reasons) if cand.reasons else "-"
129
+ print(
130
+ f" {cand.score:>5} {cand.cumtime_ms:>10.2f} {cand.time_share_pct:>6.1f}% "
131
+ f"{cand.ncalls:>7} {cand.source_rel}:{cand.lineno} {cand.function_name}{flag}"
132
+ )
133
+ print(f" reasons: {reasons}")
134
+ if cand.stageable:
135
+ print(f" next: {cand.suggested_command}")
136
+ return 0
137
+
138
+
139
+ def _cmd_stage(args: argparse.Namespace) -> int:
140
+ res = create_stage(
141
+ source_file=Path(args.source_file),
142
+ function_name=args.fn,
143
+ unit_dir=Path(args.out) if args.out else None,
144
+ rtol=args.rtol,
145
+ atol=args.atol,
146
+ power_preference=args.power_preference,
147
+ overwrite=args.overwrite,
148
+ )
149
+ if args.json:
150
+ _print_json(res)
151
+ return 0
152
+
153
+ print(f"Staged GPU unit: {res.unit_dir}")
154
+ print(f" target: {res.function.name}({res.function.signature})")
155
+ print(f" manifest: {res.manifest_path}")
156
+ print(f" shader: {res.wgsl_path}")
157
+ print(f" port: {res.port_path}")
158
+ print(f" task: {res.task_path}")
159
+ print("Next: run `gpu-shift capture <unit> -- <python command>`")
160
+ return 0
161
+
162
+
163
+ def _cmd_capture(args: argparse.Namespace) -> int:
164
+ cmd = list(args.cmd)
165
+ if cmd and cmd[0] == "--":
166
+ cmd = cmd[1:]
167
+ res = capture_unit(
168
+ unit_dir=Path(args.unit),
169
+ from_cmd=cmd,
170
+ max_calls=args.max_calls,
171
+ include_edge_cases=not args.no_edge_cases,
172
+ )
173
+ if args.json:
174
+ _print_json(res)
175
+ return 0
176
+
177
+ print(f"Captured {res.total_count} cases into {res.cases_dir}")
178
+ print(
179
+ f" captured={res.captured_count}, edge={res.edge_count}, "
180
+ f"skipped_edge={res.skipped_edge_count}"
181
+ )
182
+ print(f" source_sha256={res.source_sha256[:12]}")
183
+ for warn in res.warnings:
184
+ print(f" WARNING: {warn}")
185
+ return 0
186
+
187
+
188
+ def _cmd_diff(args: argparse.Namespace) -> int:
189
+ res = diff_unit(
190
+ unit_dir=Path(args.unit),
191
+ rtol=args.rtol,
192
+ atol=args.atol,
193
+ allow_stale=args.allow_stale,
194
+ )
195
+ if args.json:
196
+ _print_json(res)
197
+ return 0 if res.passed else 1
198
+
199
+ if res.error:
200
+ print(f"DIFF FAIL ({res.unit_name}): {res.error}")
201
+ return 1
202
+
203
+ status = "PASS" if res.passed else "FAIL"
204
+ print(
205
+ f"DIFF {status} ({res.unit_name}): "
206
+ f"{res.passed_count}/{res.total_count} passed "
207
+ f"(rtol={res.rtol}, atol={res.atol}, max_abs_err={res.max_abs_err:.2e})"
208
+ )
209
+ if res.dtype_downgraded:
210
+ print(" NOTE: original returned float64, GPU port returned float32 (within tolerance).")
211
+ for case in res.cases:
212
+ tag = "PASS" if case.passed else "FAIL"
213
+ if case.passed:
214
+ print(f" [{tag}] #{case.case_id} {case.label} (max_abs={case.max_abs_err:.2e})")
215
+ else:
216
+ print(f" [{tag}] #{case.case_id} {case.label}: {case.reason}")
217
+ if case.hint:
218
+ print(f" hint: {case.hint}")
219
+ return 0 if res.passed else 1
220
+
221
+
222
+ def _cmd_bench(args: argparse.Namespace) -> int:
223
+ res = bench_unit(
224
+ unit_dir=Path(args.unit),
225
+ warmup=args.warmup,
226
+ repeats=args.repeats,
227
+ sweep=not args.no_sweep,
228
+ update_manifest=not args.no_update_manifest,
229
+ )
230
+ if args.json:
231
+ _print_json(res)
232
+ return 0
233
+
234
+ print(f"BENCH ({res.unit_name}) on {res.adapter.device} ({res.adapter.backend_type})")
235
+ if res.recorded_points:
236
+ print("Captured workload cases:")
237
+ print(f" {'Case':<16} {'Elements':>10} {'CPU (ms)':>10} {'GPU (ms)':>10} {'Speedup':>9}")
238
+ for pt in res.recorded_points:
239
+ print(
240
+ f" {pt.label:<16} {pt.elements:>10,} "
241
+ f"{pt.cpu_ms:>10.2f} {pt.gpu_ms:>10.2f} {pt.speedup:>8.2f}x"
242
+ )
243
+ if res.sweep_points:
244
+ print("Crossover sweep (includes CPU->GPU->CPU transfers):")
245
+ print(f" {'Shape':<16} {'Elements':>10} {'CPU (ms)':>10} {'GPU (ms)':>10} {'Speedup':>9}")
246
+ for pt in res.sweep_points:
247
+ print(
248
+ f" {pt.label:<16} {pt.elements:>10,} "
249
+ f"{pt.cpu_ms:>10.2f} {pt.gpu_ms:>10.2f} {pt.speedup:>8.2f}x"
250
+ )
251
+ print(f"Verdict: {res.verdict}")
252
+ if res.manifest_updated:
253
+ print(f"Updated manifest.json: min_elements={res.crossover_elements}")
254
+ return 0
255
+
256
+
257
+ def _cmd_check(args: argparse.Namespace) -> int:
258
+ res = check_unit(
259
+ unit_dir=Path(args.unit),
260
+ require_speedup=args.require_speedup,
261
+ min_speedup=args.min_speedup,
262
+ )
263
+ if args.json:
264
+ _print_json(res)
265
+ return 0 if res.passed else 1
266
+
267
+ status = "PASS" if res.passed else "FAIL"
268
+ print(f"CHECK {status} ({res.unit_name})")
269
+ for chk in res.checks:
270
+ tag = "PASS" if chk.passed else "FAIL"
271
+ print(f" [{tag}] {chk.name}: {chk.detail}")
272
+ return 0 if res.passed else 1
273
+
274
+
275
+ def _cmd_enable(args: argparse.Namespace) -> int:
276
+ res = enable_unit(Path(args.unit), force=args.force)
277
+ if args.json:
278
+ _print_json(res)
279
+ return 0
280
+ print(res.message)
281
+ return 0
282
+
283
+
284
+ def _cmd_disable(args: argparse.Namespace) -> int:
285
+ res = disable_unit(Path(args.unit))
286
+ if args.json:
287
+ _print_json(res)
288
+ return 0
289
+ print(res.message)
290
+ return 0
291
+
292
+
293
+ def _cmd_run(args: argparse.Namespace) -> int:
294
+ res = run_workflow(
295
+ cmd=list(args.cmd),
296
+ source_file=Path(args.file) if args.file else None,
297
+ function_name=args.fn,
298
+ unit_dir=Path(args.out) if args.out else None,
299
+ agent_cmd=args.agent,
300
+ auto_enable=not args.no_enable,
301
+ )
302
+ if args.json:
303
+ _print_json(res)
304
+ return 0 if res.passed else 1
305
+
306
+ print(f"RUN [{res.stage}] ({res.function_name})")
307
+ print(f" unit: {res.unit_dir}")
308
+ print(f" task: {res.task_path}")
309
+ print(f" {res.message}")
310
+ return 0 if res.passed else 1
311
+
312
+
313
+ def _cmd_report(args: argparse.Namespace) -> int:
314
+ res = generate_report(
315
+ unit_dir=Path(args.unit),
316
+ warmup=args.warmup,
317
+ repeats=args.repeats,
318
+ )
319
+ if args.json:
320
+ _print_json(res)
321
+ return 0 if res.check_passed else 1
322
+
323
+ print(f"Generated PR report for {res.unit_name}:")
324
+ print(f" markdown: {res.report_md_path}")
325
+ print(f" card svg: {res.card_svg_path}")
326
+ print(
327
+ f" check={'PASS' if res.check_passed else 'FAIL'}, "
328
+ f"peak={res.peak_speedup:.2f}x, crossover={res.crossover_elements}"
329
+ )
330
+ return 0 if res.check_passed else 1
331
+
332
+
333
+ def _cmd_setup(args: argparse.Namespace) -> int:
334
+ res = setup_agents(
335
+ agents=args.agent if args.agent else None,
336
+ remove=args.remove,
337
+ dry_run=args.dry_run,
338
+ backup=not args.no_backup,
339
+ )
340
+ if args.json:
341
+ _print_json(res)
342
+ return 0
343
+
344
+ mode = "remove" if res.remove else "install"
345
+ suffix = " (dry-run)" if res.dry_run else ""
346
+ print(f"gpu-shift setup ({mode}{suffix}):")
347
+ for act in res.actions:
348
+ print(f" - {act.agent:<10} {act.status}")
349
+ if act.mcp_config_path:
350
+ print(f" mcp: {act.mcp_config_path}")
351
+ if act.skill_path:
352
+ print(f" skill: {act.skill_path}")
353
+ if act.backup_path:
354
+ print(f" bak: {act.backup_path}")
355
+ return 0
356
+
357
+
358
+ def _cmd_mcp(_args: argparse.Namespace) -> int:
359
+ return serve_stdio()
360
+
361
+
362
+ def build_parser() -> argparse.ArgumentParser:
363
+ parser = argparse.ArgumentParser(
364
+ prog="gpu-shift",
365
+ description="Shift slow Python/NumPy CPU functions to any GPU via WebGPU/WGSL.",
366
+ )
367
+ parser.add_argument(
368
+ "--version",
369
+ action="version",
370
+ version=f"%(prog)s {__version__}",
371
+ )
372
+
373
+ subparsers = parser.add_subparsers(dest="command")
374
+
375
+ # doctor
376
+ p_doctor = subparsers.add_parser(
377
+ "doctor",
378
+ help="Check available WebGPU adapters and run a WGSL compute smoke test.",
379
+ )
380
+ p_doctor.add_argument(
381
+ "--power-preference",
382
+ choices=("high-performance", "low-power"),
383
+ default="high-performance",
384
+ help="Preferred WebGPU adapter power profile.",
385
+ )
386
+ p_doctor.add_argument("--json", action="store_true", help="Output JSON.")
387
+ p_doctor.set_defaults(func=_cmd_doctor)
388
+
389
+ # demo
390
+ p_demo = subparsers.add_parser(
391
+ "demo",
392
+ help="Run a live GPU demo (diff, VRAM soak, crossover sweep).",
393
+ )
394
+ p_demo.add_argument(
395
+ "--power-preference",
396
+ choices=("high-performance", "low-power"),
397
+ default="high-performance",
398
+ )
399
+ p_demo.add_argument("--json", action="store_true", help="Output JSON.")
400
+ p_demo.set_defaults(func=_cmd_demo)
401
+
402
+ # scan
403
+ p_scan = subparsers.add_parser(
404
+ "scan",
405
+ help="Scan a Python workload and rank GPU offload candidates.",
406
+ )
407
+ p_scan.add_argument("--root", help="Project root directory (defaults to CWD).")
408
+ p_scan.add_argument("--top", type=int, default=8, help="Max candidates to show.")
409
+ p_scan.add_argument("--json", action="store_true", help="Output JSON.")
410
+ p_scan.add_argument(
411
+ "cmd",
412
+ nargs=argparse.REMAINDER,
413
+ help="Command after `--` (e.g. -- python examples/denoise/demo.py).",
414
+ )
415
+ p_scan.set_defaults(func=_cmd_scan)
416
+
417
+ # stage
418
+ p_stage = subparsers.add_parser(
419
+ "stage",
420
+ help="Stage kernels/<fn>/ without modifying the original source file.",
421
+ )
422
+ p_stage.add_argument("source_file", help="Path to the Python source file.")
423
+ p_stage.add_argument("--fn", required=True, help="Top-level function name to port.")
424
+ p_stage.add_argument("--out", help="Custom output unit directory.")
425
+ p_stage.add_argument("--rtol", type=float, default=1e-4, help="Default relative tolerance.")
426
+ p_stage.add_argument("--atol", type=float, default=1e-5, help="Default absolute tolerance.")
427
+ p_stage.add_argument(
428
+ "--power-preference",
429
+ choices=("high-performance", "low-power"),
430
+ default="high-performance",
431
+ )
432
+ p_stage.add_argument("--overwrite", action="store_true", help="Overwrite existing unit dir.")
433
+ p_stage.add_argument("--json", action="store_true", help="Output JSON.")
434
+ p_stage.set_defaults(func=_cmd_stage)
435
+
436
+ # capture
437
+ p_capture = subparsers.add_parser(
438
+ "capture",
439
+ help="Capture CPU reference outputs (.npz) and GPU edge-case traps.",
440
+ )
441
+ p_capture.add_argument("unit", help="Path to the kernels/<fn> unit directory.")
442
+ p_capture.add_argument("--max-calls", type=int, default=16, help="Max real calls to capture.")
443
+ p_capture.add_argument(
444
+ "--no-edge-cases",
445
+ action="store_true",
446
+ help="Skip synthetic GPU edge cases.",
447
+ )
448
+ p_capture.add_argument("--json", action="store_true", help="Output JSON.")
449
+ p_capture.add_argument(
450
+ "--from-cmd",
451
+ action="store_true",
452
+ help="Optional marker before `-- <python command>`.",
453
+ )
454
+ p_capture.add_argument(
455
+ "cmd",
456
+ nargs=argparse.REMAINDER,
457
+ help="Command to run under CPU capture (e.g. -- python demo.py).",
458
+ )
459
+ p_capture.set_defaults(func=_cmd_capture)
460
+
461
+ # diff
462
+ p_diff = subparsers.add_parser(
463
+ "diff",
464
+ help="Replay captured cases against the GPU port and verify numerical parity.",
465
+ )
466
+ p_diff.add_argument("unit", help="Path to the kernels/<fn> unit directory.")
467
+ p_diff.add_argument("--rtol", type=float, default=None, help="Override relative tolerance.")
468
+ p_diff.add_argument("--atol", type=float, default=None, help="Override absolute tolerance.")
469
+ p_diff.add_argument(
470
+ "--allow-stale",
471
+ action="store_true",
472
+ help="Run even if the original source file changed since capture.",
473
+ )
474
+ p_diff.add_argument("--json", action="store_true", help="Output JSON.")
475
+ p_diff.set_defaults(func=_cmd_diff)
476
+
477
+ # bench
478
+ p_bench = subparsers.add_parser(
479
+ "bench",
480
+ help="Benchmark end-to-end CPU vs GPU speed and detect min_elements crossover.",
481
+ )
482
+ p_bench.add_argument("unit", help="Path to the kernels/<fn> unit directory.")
483
+ p_bench.add_argument("--warmup", type=int, default=2, help="Warmup iterations.")
484
+ p_bench.add_argument("--repeats", type=int, default=5, help="Timed iterations.")
485
+ p_bench.add_argument("--no-sweep", action="store_true", help="Skip size sweep.")
486
+ p_bench.add_argument(
487
+ "--no-update-manifest",
488
+ action="store_true",
489
+ help="Do not persist min_elements into manifest.json.",
490
+ )
491
+ p_bench.add_argument("--json", action="store_true", help="Output JSON.")
492
+ p_bench.set_defaults(func=_cmd_bench)
493
+
494
+ # check
495
+ p_check = subparsers.add_parser(
496
+ "check",
497
+ help="Run final verification check (freshness, WGSL, diff, native VRAM soak).",
498
+ )
499
+ p_check.add_argument("unit", help="Path to the kernels/<fn> unit directory.")
500
+ p_check.add_argument(
501
+ "--require-speedup",
502
+ action="store_true",
503
+ help="Also require bench speedup above --min-speedup.",
504
+ )
505
+ p_check.add_argument(
506
+ "--min-speedup",
507
+ type=float,
508
+ default=1.1,
509
+ help="Minimum peak speedup when --require-speedup is set.",
510
+ )
511
+ p_check.add_argument("--json", action="store_true", help="Output JSON.")
512
+ p_check.set_defaults(func=_cmd_check)
513
+
514
+ # enable
515
+ p_enable = subparsers.add_parser(
516
+ "enable",
517
+ help="Enable a verified GPU port in the original file (with crossover + CPU fallback).",
518
+ )
519
+ p_enable.add_argument("unit", help="Path to the kernels/<fn> unit directory.")
520
+ p_enable.add_argument("--force", action="store_true", help="Enable even if check not passed.")
521
+ p_enable.add_argument("--json", action="store_true", help="Output JSON.")
522
+ p_enable.set_defaults(func=_cmd_enable)
523
+
524
+ # disable
525
+ p_disable = subparsers.add_parser(
526
+ "disable",
527
+ help="Disable the GPU port and restore the original file byte-for-byte.",
528
+ )
529
+ p_disable.add_argument("unit", help="Path to the kernels/<fn> unit directory.")
530
+ p_disable.add_argument("--json", action="store_true", help="Output JSON.")
531
+ p_disable.set_defaults(func=_cmd_disable)
532
+
533
+ # run
534
+ p_run = subparsers.add_parser(
535
+ "run",
536
+ help="Stateful single-command loop: scan, stage, capture, diff, check, bench, enable.",
537
+ )
538
+ p_run.add_argument("--file", help="Optional target Python file (skips scanner auto-pick).")
539
+ p_run.add_argument("--fn", help="Optional target function name (use with --file).")
540
+ p_run.add_argument("--out", help="Custom unit directory.")
541
+ p_run.add_argument(
542
+ "--agent",
543
+ help="Optional agent CLI command reading TASK.md on stdin (otherwise stops at TASK.md).",
544
+ )
545
+ p_run.add_argument("--no-enable", action="store_true", help="Stop before enabling source file.")
546
+ p_run.add_argument("--json", action="store_true", help="Output JSON.")
547
+ p_run.add_argument(
548
+ "cmd",
549
+ nargs=argparse.REMAINDER,
550
+ help="Workload command after `--` (e.g. -- python app.py).",
551
+ )
552
+ p_run.set_defaults(func=_cmd_run)
553
+
554
+ # report
555
+ p_report = subparsers.add_parser(
556
+ "report",
557
+ help="Generate PR-ready report/REPORT.md and report/card.svg for a unit.",
558
+ )
559
+ p_report.add_argument("unit", help="Path to the kernels/<fn> unit directory.")
560
+ p_report.add_argument("--warmup", type=int, default=2)
561
+ p_report.add_argument("--repeats", type=int, default=5)
562
+ p_report.add_argument("--json", action="store_true", help="Output JSON.")
563
+ p_report.set_defaults(func=_cmd_report)
564
+
565
+ # setup
566
+ p_setup = subparsers.add_parser(
567
+ "setup",
568
+ help="Register gpu-shift MCP server and SKILL.md with installed coding agents.",
569
+ )
570
+ p_setup.add_argument(
571
+ "--agent",
572
+ action="append",
573
+ choices=SUPPORTED_AGENTS,
574
+ help="Target specific agent(s); defaults to auto-detecting installed ones.",
575
+ )
576
+ p_setup.add_argument("--remove", action="store_true", help="Undo registration.")
577
+ p_setup.add_argument("--dry-run", action="store_true", help="Show planned changes only.")
578
+ p_setup.add_argument("--no-backup", action="store_true", help="Skip .gpu-shift.bak backup.")
579
+ p_setup.add_argument("--json", action="store_true", help="Output JSON.")
580
+ p_setup.set_defaults(func=_cmd_setup)
581
+
582
+ # mcp
583
+ p_mcp = subparsers.add_parser(
584
+ "mcp",
585
+ help="Run the stdio JSON-RPC 2.0 MCP server for coding agents.",
586
+ )
587
+ p_mcp.set_defaults(func=_cmd_mcp)
588
+
589
+ return parser
590
+
591
+
592
+ def main(argv: list[str] | None = None) -> int:
593
+ parser = build_parser()
594
+ args = parser.parse_args(argv)
595
+ if not hasattr(args, "func"):
596
+ parser.print_help()
597
+ return 0
598
+ try:
599
+ return int(args.func(args))
600
+ except Exception as exc: # noqa: BLE001
601
+ if getattr(args, "json", False):
602
+ _print_json({"error": str(exc), "type": type(exc).__name__})
603
+ else:
604
+ print(f"Error: {exc}", file=sys.stderr)
605
+ return 1
606
+
607
+
608
+ if __name__ == "__main__":
609
+ sys.exit(main())