"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
Add Nsight Graphics harness
aimidie2ccb9daedc4
diff --git a/.gitignore b/.gitignoreindex 6eb435674..69f258fb5 100644--- a/.gitignore+++ b/.gitignore@@ -81,6 +81,7 @@!/rms/!/renderdoc/!/cloudcompare/+!/nsight-graphics/# Step 5: Inside each software dir, ignore everything (including dotfiles)/gimp/*@@ -137,6 +138,8 @@/renderdoc/.*/cloudcompare/*/cloudcompare/.*+/nsight-graphics/*+/nsight-graphics/.*# Step 6: ...except agent-harness/!/gimp/agent-harness/@@ -168,6 +171,7 @@!/rms/agent-harness/!/renderdoc/agent-harness/!/cloudcompare/agent-harness/+!/nsight-graphics/agent-harness/# Step 7: Ignore build artifacts within allowed dirs**/__pycache__/diff --git a/README.md b/README.mdindex ece60f457..1dc406e7b 100644--- a/README.md+++ b/README.md@@ -477,7 +477,7 @@ The catalog auto-updates whenever `registry.json` changes β new community CLIs| **π Communication & Collaboration** | Automate meeting scheduling, participant management, recording retrieval, and reporting through structured CLI | Zoom, Jitsi Meet, BigBlueButton, Mattermost || **π Diagramming & Visualization** | Create and manipulate diagrams, flowcharts, architecture diagrams, and visual documentation programmatically | Draw.io (diagrams.net), Mermaid, PlantUML, Excalidraw, yEd || **π Network & Infrastructure** | Manage network services, DNS, ad-blocking, and infrastructure through structured CLI commands | AdGuardHome |-| **π¬ Graphics & GPU Debugging** | Analyze GPU frame captures, inspect pipeline state, export shaders, and diff rendering state | RenderDoc |+| **π¬ Graphics & GPU Debugging** | Analyze GPU frame captures, inspect pipeline state, export shaders, diff rendering state, and orchestrate Nsight Graphics captures | RenderDoc, Nsight Graphics || **π¬ Video & Subtitles** | Transcribe speech, translate subtitles, burn styled captions into video β full captioning pipeline | VideoCaptioner || **β¨ AI Content Generation** | Generate professional deliverables (slides, docs, diagrams, websites, research reports) through AI-powered cloud APIs | [AnyGen](https://www.anygen.io), Gamma, Beautiful.ai, Tome |@@ -826,6 +826,13 @@ Each application received complete, production-ready CLI interfaces β not demo<td align="center">β 19</td></tr><tr>+<td align="center"><strong>π© Nsight Graphics</strong></td>+<td>GPU Debugging & Profiling</td>+<td><code>cli-anything-nsight-graphics</code></td>+<td>Official ngfx / ngfx-capture orchestration</td>+<td align="center">β <a href="nsight-graphics/agent-harness/">New</a></td>+</tr>+<tr><td align="center"><strong>π ²π ² CloudCompare</strong></td><td>3D Point Cloud & Mesh</td><td><code>cli-anything-cloudcompare</code></td>@@ -947,7 +954,8 @@ cli-anything/βββ π¦ ollama/agent-harness/ # Ollama CLI (98 tests)βββ π¨ sketch/agent-harness/ # Sketch CLI (19 tests, Node.js)βββ π¬ renderdoc/agent-harness/ # RenderDoc CLI (59 tests)-βββ π¬ videocaptioner/agent-harness/ # VideoCaptioner CLI (26 tests)+βββ π© nsight-graphics/agent-harness/ # Nsight Graphics CLI (new)+βββ π¬ videocaptioner/agent-harness/ # VideoCaptioner CLI (26 tests)βββ βοΈ cloudcompare/agent-harness/ # CloudCompare CLI (88 tests)```diff --git a/nsight-graphics/agent-harness/HARNESS.md b/nsight-graphics/agent-harness/HARNESS.mdnew file mode 100644index 000000000..8267c0fa3--- /dev/null+++ b/nsight-graphics/agent-harness/HARNESS.md@@ -0,0 +1,84 @@+# HARNESS.md β Nsight Graphics CLI Harness Specification++## Overview++This harness wraps the official **NVIDIA Nsight Graphics** command-line tools+into a Click-based CLI named `cli-anything-nsight-graphics`.++V1 is intentionally **orchestration-focused**:++- installation and capability probing+- detached launch and PID attach via `ngfx.exe`+- Frame Debugger capture+- GPU Trace capture and auto-export+- Generate C++ Capture++It does **not** attempt RenderDoc-style offline object inspection of pipeline+state, shaders, textures, or resources.++## Architecture++```text+agent-harness/+βββ HARNESS.md+βββ NSIGHT_GRAPHICS.md+βββ setup.py+βββ cli_anything/+ βββ nsight_graphics/+ βββ __init__.py+ βββ __main__.py+ βββ README.md+ βββ nsight_graphics_cli.py+ βββ core/+ β βββ doctor.py+ β βββ launch.py+ β βββ frame.py+ β βββ gpu_trace.py+ β βββ cpp_capture.py+ βββ utils/+ β βββ nsight_graphics_backend.py+ β βββ output.py+ β βββ errors.py+ β βββ repl_skin.py+ βββ skills/+ β βββ SKILL.md+ βββ tests/+ βββ TEST.md+ βββ test_core.py+ βββ test_full_e2e.py+```++## Command Groups++| Group | Commands |+|-------|----------|+| `doctor` | `info` |+| `launch` | `detached`, `attach` |+| `frame` | `capture` |+| `gpu-trace` | `capture` |+| `cpp` | `capture` |++## Backend Strategy++1. Resolve Nsight executables from `NSIGHT_GRAPHICS_PATH`, `PATH`, then common+ Windows install directories.+2. Detect compatibility mode:+ - `unified`: legacy `ngfx.exe` activity-driven CLI+ - `split`: modern `ngfx-capture` / `ngfx-replay` present+3. Prefer `ngfx.exe` when available, because it covers launch, attach,+ GPU Trace, and Generate C++ Capture.+4. Use version-tolerant artifact discovery by diffing the output directory+ before and after a command instead of depending on one filename.++## Testing Strategy++- `test_core.py`: mock-based unit tests for discovery, parsing, command+ construction, error handling, and CLI help.+- `test_full_e2e.py`: conditional tests using a real Nsight installation and a+ user-supplied test executable via environment variables.++## Notes++- V1 is Windows-first and only claims verified support on Windows hosts.+- Split replay binaries are detected and reported by `doctor info`, but replay+ helper commands are intentionally deferred.diff --git a/nsight-graphics/agent-harness/NSIGHT_GRAPHICS.md b/nsight-graphics/agent-harness/NSIGHT_GRAPHICS.mdnew file mode 100644index 000000000..73221ed4f--- /dev/null+++ b/nsight-graphics/agent-harness/NSIGHT_GRAPHICS.md@@ -0,0 +1,39 @@+# NSIGHT_GRAPHICS.md β Software-Specific SOP++## About Nsight Graphics++NVIDIA Nsight Graphics is a graphics debugging and profiling suite for Direct3D,+Vulkan, OpenGL, and related GPU workflows. Depending on the installed version,+it exposes either:++- a **legacy unified CLI** through `ngfx.exe` with activity selection+- a newer **split tool** layout including `ngfx-capture` and `ngfx-replay`++This harness targets the official command-line interfaces rather than the GUI.++## V1 Coverage++### Supported++- installation detection and capability probing+- listing detected installed versions+- detached app launch+- attach to a running PID with an activity+- Frame Debugger capture orchestration+- GPU Trace capture orchestration+- Generate C++ Capture orchestration+- artifact discovery in output directories++### Explicitly Deferred++- replay-helper public commands+- pipeline/resource/shader inspection APIs+- deep analysis comparable to RenderDoc's Python bindings++## Compatibility Notes++- On older Windows installs, `ngfx.exe --help-all` is the primary source of+ truth for supported activities and activity options.+- On newer installs, `ngfx-capture` / `ngfx-replay` may exist alongside `ngfx`.+- This harness prefers capability detection over hard-coded version branching.+- `--nsight-path` can explicitly select one installation when multiple versions coexist.diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/README.md b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/README.mdnew file mode 100644index 000000000..9cff828c4--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/README.md@@ -0,0 +1,177 @@+# cli-anything-nsight-graphics++Windows-first CLI harness for the official [NVIDIA Nsight Graphics](https://developer.nvidia.com/nsight-graphics) tools.++This package focuses on **orchestrating** Nsight Graphics activities from the+terminal:++- installation and capability probing+- detached launch and PID attach+- Frame Debugger capture+- GPU Trace capture and auto-export+- Generate C++ Capture++It does not provide RenderDoc-style offline inspection of shaders, pipeline+state, textures, or resources.++## Installation++```bash+cd nsight-graphics/agent-harness+pip install -e .+```++## Prerequisites++- Windows host recommended and verified for v1+- NVIDIA Nsight Graphics installed+- One of:+ - `ngfx.exe`+ - or newer split tools such as `ngfx-capture` / `ngfx-replay`++If Nsight Graphics is not on `PATH`, set:++```powershell+$env:NSIGHT_GRAPHICS_PATH = "C:\Program Files\NVIDIA Corporation\Nsight Graphics 2023.3.2\host\windows-desktop-nomad-x64"+```++You may also point `NSIGHT_GRAPHICS_PATH` directly at `ngfx.exe`.++## Quick Start++### Inspect the installation++```bash+cli-anything-nsight-graphics --json doctor info+cli-anything-nsight-graphics --json doctor versions+```++### Choose a specific installed version++```bash+cli-anything-nsight-graphics ^+ --nsight-path "C:\Program Files\NVIDIA Corporation\Nsight Graphics 2024.2\host\windows-desktop-nomad-x64" ^+ --json doctor info+```++### Launch a target detached++```bash+cli-anything-nsight-graphics launch detached ^+ --activity "Frame Debugger" ^+ --exe "C:\VulkanSDK\1.3.290.0\Bin\vkcube.exe"+```++### Attach to a running PID++```bash+cli-anything-nsight-graphics launch attach ^+ --activity "Frame Debugger" ^+ --pid 12345+```++### Capture a frame++```bash+cli-anything-nsight-graphics --output-dir D:\captures frame capture ^+ --exe "C:\VulkanSDK\1.3.290.0\Bin\vkcube.exe" ^+ --wait-frames 10+```++### Collect a GPU trace++```bash+cli-anything-nsight-graphics --output-dir D:\traces gpu-trace capture ^+ --exe "C:\VulkanSDK\1.3.290.0\Bin\vkcube.exe" ^+ --start-after-ms 1000 ^+ --limit-to-frames 1 ^+ --auto-export+```++### Generate a C++ capture++```bash+cli-anything-nsight-graphics --output-dir D:\cpp cpp capture ^+ --exe "C:\VulkanSDK\1.3.290.0\Bin\vkcube.exe" ^+ --wait-seconds 5+```++## Command Reference++### Global Options++| Option | Description |+|--------|-------------|+| `--json` | JSON output mode |+| `--debug` | Include traceback details in errors |+| `--nsight-path` | Explicit install directory or executable to use when multiple Nsight versions are installed |+| `--project` | Nsight Graphics project file |+| `--output-dir` | Output directory for captures or exported artifacts |+| `--hostname` | Remote host for Nsight launch/attach |+| `--platform` | Target platform string passed to Nsight |++### Command Groups++| Group | Command | Purpose |+|-------|---------|---------|+| `doctor` | `info` | Probe installed binaries, version, activities, compatibility mode |+| `doctor` | `versions` | List detected Nsight Graphics installs and show which one is selected |+| `launch` | `detached` | Launch a target under Nsight without blocking the CLI |+| `launch` | `attach` | Attach Nsight to a running PID |+| `frame` | `capture` | Trigger a Frame Debugger capture |+| `gpu-trace` | `capture` | Trigger a GPU Trace capture |+| `cpp` | `capture` | Trigger Generate C++ Capture |++## JSON Output++All commands support `--json`. Results include normalized fields such as:++- `ok`+- `returncode`+- `command`+- `stdout`+- `stderr`+- `tool_mode`++Capture-producing commands also include:++- `activity`+- `output_dir`+- `artifacts`++## Environment Variables++| Variable | Purpose |+|----------|---------|+| `NSIGHT_GRAPHICS_PATH` | Override executable discovery |+| `NSIGHT_GRAPHICS_TEST_EXE` | E2E target executable |+| `NSIGHT_GRAPHICS_TEST_ARGS` | Optional E2E target arguments |+| `NSIGHT_GRAPHICS_TEST_WORKDIR` | Optional E2E working directory |++## E2E Test Prerequisites++The E2E suite assumes:++- Nsight Graphics is installed and discoverable+- `NSIGHT_GRAPHICS_TEST_EXE` points to a graphics workload that Nsight can+ launch or capture+- optional args/workdir are provided if the test target requires them++Typical examples include `vkcube.exe`, game samples, or internal engine demos.++## Multiple Installations++If you have several Nsight Graphics versions installed, the CLI chooses in this order:++1. `--nsight-path`+2. `NSIGHT_GRAPHICS_PATH`+3. `PATH`+4. default Windows install directories++Use `doctor versions` to inspect what is installed and which executable is currently selected.++Entries marked `registered-only` came from the Windows uninstall registry but do+not currently have a discovered Nsight executable path. They are useful for+diagnosis, but not enough by themselves to launch captures. The harness also+scans standard `Program Files` locations on all fixed Windows drives, so+non-`C:` installs can still be promoted to normal filesystem-backed entries.diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/__init__.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/__init__.pynew file mode 100644index 000000000..ec369d319--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/__init__.py@@ -0,0 +1,3 @@+"""Nsight Graphics CLI harness package."""++__version__ = "0.1.0"diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/__main__.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/__main__.pynew file mode 100644index 000000000..e2eafb3b5--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/__main__.py@@ -0,0 +1,7 @@+"""Module entrypoint for python -m cli_anything.nsight_graphics."""++from cli_anything.nsight_graphics.nsight_graphics_cli import main+++if __name__ == "__main__":+ main()diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/__init__.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/__init__.pynew file mode 100644index 000000000..99a5a942b--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/__init__.py@@ -0,0 +1 @@+"""Core command implementations for Nsight Graphics."""diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/cpp_capture.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/cpp_capture.pynew file mode 100644index 000000000..6cc8b13d6--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/cpp_capture.py@@ -0,0 +1,65 @@+"""Generate C++ Capture orchestration."""++from __future__ import annotations++from typing import Sequence++from cli_anything.nsight_graphics.utils import nsight_graphics_backend as backend+++def capture_cpp(+ *,+ nsight_path: str | None,+ project: str | None,+ output_dir: str | None,+ hostname: str | None,+ platform_name: str | None,+ exe: str | None,+ working_dir: str | None,+ args: Sequence[str],+ envs: Sequence[str],+ wait_seconds: int | None,+ wait_hotkey: bool,+) -> dict:+ """Run Generate C++ Capture."""+ report = backend.probe_installation(nsight_path=nsight_path)+ binaries = report["binaries"]+ backend.require_binary(binaries, "ngfx")+ backend.require_launch_target(project=project, exe=exe)++ backend.ensure_exactly_one(+ "c++ capture trigger",+ {+ "wait_seconds": wait_seconds is not None,+ "wait_hotkey": wait_hotkey,+ },+ )++ extra_args: list[str] = []+ if wait_seconds is not None:+ extra_args.extend(["--wait-seconds", str(wait_seconds)])+ else:+ extra_args.append("--wait-hotkey")++ command = backend.build_unified_command(+ binaries,+ activity="Generate C++ Capture",+ project=project,+ output_dir=output_dir,+ hostname=hostname,+ platform_name=platform_name,+ exe=exe,+ working_dir=working_dir,+ args=args,+ envs=envs,+ extra_args=extra_args,+ )+ result = backend.run_with_artifacts(+ command,+ output_roots=backend.activity_artifact_roots("Generate C++ Capture", output_dir),+ timeout=600,+ )+ result["tool_mode"] = "unified"+ result["activity"] = "Generate C++ Capture"+ result["output_dir"] = output_dir or backend.default_output_dir()+ return resultdiff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/doctor.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/doctor.pynew file mode 100644index 000000000..a59815945--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/doctor.py@@ -0,0 +1,15 @@+"""Doctor commands."""++from __future__ import annotations++from cli_anything.nsight_graphics.utils import nsight_graphics_backend as backend+++def get_installation_report(nsight_path: str | None = None) -> dict:+ """Return the current Nsight Graphics installation report."""+ return backend.probe_installation(nsight_path=nsight_path)+++def list_installations(nsight_path: str | None = None) -> dict:+ """Return all detected Nsight Graphics installations."""+ return backend.list_installations(nsight_path=nsight_path)diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/frame.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/frame.pynew file mode 100644index 000000000..7767ca72c--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/frame.py@@ -0,0 +1,110 @@+"""Frame capture orchestration."""++from __future__ import annotations++from typing import Sequence++from cli_anything.nsight_graphics.utils import nsight_graphics_backend as backend+++def capture_frame(+ *,+ nsight_path: str | None,+ project: str | None,+ output_dir: str | None,+ hostname: str | None,+ platform_name: str | None,+ exe: str | None,+ working_dir: str | None,+ args: Sequence[str],+ envs: Sequence[str],+ wait_seconds: int | None,+ wait_frames: int | None,+ wait_hotkey: bool,+ export_frame_perf_metrics: bool,+ export_range_perf_metrics: bool,+) -> dict:+ """Run a Frame Debugger capture."""+ report = backend.probe_installation(nsight_path=nsight_path)+ binaries = report["binaries"]+ artifact_roots = backend.activity_artifact_roots("Frame Debugger", output_dir)++ if binaries.get("ngfx"):+ backend.require_launch_target(project=project, exe=exe)+ backend.ensure_exactly_one(+ "frame trigger",+ {+ "wait_seconds": wait_seconds is not None,+ "wait_frames": wait_frames is not None,+ "wait_hotkey": wait_hotkey,+ },+ )++ extra_args: list[str] = []+ if wait_seconds is not None:+ extra_args.extend(["--wait-seconds", str(wait_seconds)])+ elif wait_frames is not None:+ extra_args.extend(["--wait-frames", str(wait_frames)])+ else:+ extra_args.append("--wait-hotkey")++ if export_frame_perf_metrics:+ extra_args.append("--export-frame-perf-metrics")+ if export_range_perf_metrics:+ extra_args.append("--export-range-perf-metrics")++ command = backend.build_unified_command(+ binaries,+ activity="Frame Debugger",+ project=project,+ output_dir=output_dir,+ hostname=hostname,+ platform_name=platform_name,+ exe=exe,+ working_dir=working_dir,+ args=args,+ envs=envs,+ extra_args=extra_args,+ )+ result = backend.run_with_artifacts(+ command,+ output_roots=artifact_roots,+ timeout=300,+ )+ result["tool_mode"] = "unified"+ elif binaries.get("ngfx_capture"):+ if project:+ raise RuntimeError(+ "Project-driven frame capture fallback requires ngfx.exe; "+ "split ngfx-capture mode currently needs --exe."+ )+ if export_frame_perf_metrics or export_range_perf_metrics:+ raise RuntimeError(+ "Frame performance export flags require ngfx.exe Frame Debugger mode."+ )+ if not exe:+ raise ValueError("Specify --exe for split ngfx-capture mode.")++ command = backend.build_split_capture_command(+ binaries,+ exe=exe,+ output_dir=output_dir,+ working_dir=working_dir,+ args=args,+ envs=envs,+ wait_seconds=wait_seconds,+ wait_frames=wait_frames,+ wait_hotkey=wait_hotkey,+ )+ result = backend.run_with_artifacts(+ command,+ output_roots=artifact_roots,+ timeout=300,+ )+ result["tool_mode"] = "split"+ else:+ raise RuntimeError(backend.INSTALL_INSTRUCTIONS)++ result["activity"] = "Frame Debugger"+ result["output_dir"] = output_dir or backend.default_output_dir()+ return resultdiff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/gpu_trace.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/gpu_trace.pynew file mode 100644index 000000000..56b88f10d--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/gpu_trace.py@@ -0,0 +1,107 @@+"""GPU Trace orchestration."""++from __future__ import annotations++from typing import Sequence++from cli_anything.nsight_graphics.utils import nsight_graphics_backend as backend+++def capture_trace(+ *,+ nsight_path: str | None,+ project: str | None,+ output_dir: str | None,+ hostname: str | None,+ platform_name: str | None,+ exe: str | None,+ working_dir: str | None,+ args: Sequence[str],+ envs: Sequence[str],+ start_after_frames: int | None,+ start_after_submits: int | None,+ start_after_ms: int | None,+ start_after_hotkey: bool,+ max_duration_ms: int | None,+ limit_to_frames: int | None,+ limit_to_submits: int | None,+ auto_export: bool,+ architecture: str | None,+ metric_set_id: str | None,+ multi_pass_metrics: bool,+ real_time_shader_profiler: bool,+) -> dict:+ """Run a GPU Trace capture."""+ report = backend.probe_installation(nsight_path=nsight_path)+ binaries = report["binaries"]+ backend.require_binary(binaries, "ngfx")+ backend.require_launch_target(project=project, exe=exe)++ backend.ensure_exactly_one(+ "gpu trace start trigger",+ {+ "start_after_frames": start_after_frames is not None,+ "start_after_submits": start_after_submits is not None,+ "start_after_ms": start_after_ms is not None,+ "start_after_hotkey": start_after_hotkey,+ },+ )+ backend.ensure_at_most_one(+ "gpu trace stop limit",+ {+ "limit_to_frames": limit_to_frames is not None,+ "limit_to_submits": limit_to_submits is not None,+ },+ )+ if metric_set_id and not architecture:+ raise ValueError("--metric-set-id requires --architecture.")++ extra_args: list[str] = []+ if start_after_frames is not None:+ extra_args.extend(["--start-after-frames", str(start_after_frames)])+ elif start_after_submits is not None:+ extra_args.extend(["--start-after-submits", str(start_after_submits)])+ elif start_after_ms is not None:+ extra_args.extend(["--start-after-ms", str(start_after_ms)])+ else:+ extra_args.append("--start-after-hotkey")++ if max_duration_ms is not None:+ extra_args.extend(["--max-duration-ms", str(max_duration_ms)])+ if limit_to_frames is not None:+ extra_args.extend(["--limit-to-frames", str(limit_to_frames)])+ if limit_to_submits is not None:+ extra_args.extend(["--limit-to-submits", str(limit_to_submits)])+ if auto_export:+ extra_args.append("--auto-export")+ if architecture:+ extra_args.extend(["--architecture", architecture])+ if metric_set_id:+ extra_args.extend(["--metric-set-id", str(metric_set_id)])+ if multi_pass_metrics:+ extra_args.append("--multi-pass-metrics")+ if real_time_shader_profiler:+ extra_args.append("--real-time-shader-profiler")++ command = backend.build_unified_command(+ binaries,+ activity="GPU Trace Profiler",+ project=project,+ output_dir=output_dir,+ hostname=hostname,+ platform_name=platform_name,+ exe=exe,+ working_dir=working_dir,+ args=args,+ envs=envs,+ extra_args=extra_args,+ )+ result = backend.run_with_artifacts(+ command,+ output_roots=backend.activity_artifact_roots("GPU Trace Profiler", output_dir),+ timeout=600,+ )+ result["tool_mode"] = "unified"+ result["activity"] = "GPU Trace Profiler"+ result["output_dir"] = output_dir or backend.default_output_dir()+ return resultdiff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/launch.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/launch.pynew file mode 100644index 000000000..ea34c7d20--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/core/launch.py@@ -0,0 +1,76 @@+"""Launch and attach helpers."""++from __future__ import annotations++from typing import Sequence++from cli_anything.nsight_graphics.utils import nsight_graphics_backend as backend+++def launch_detached(+ *,+ nsight_path: str | None,+ activity: str,+ project: str | None,+ output_dir: str | None,+ hostname: str | None,+ platform_name: str | None,+ exe: str | None,+ working_dir: str | None,+ args: Sequence[str],+ envs: Sequence[str],+) -> dict:+ """Launch a target under Nsight and exit immediately."""+ report = backend.probe_installation(nsight_path=nsight_path)+ binaries = report["binaries"]+ backend.require_binary(binaries, "ngfx")+ backend.require_launch_target(project=project, exe=exe)++ command = backend.build_unified_command(+ binaries,+ activity=activity,+ project=project,+ output_dir=output_dir,+ hostname=hostname,+ platform_name=platform_name,+ exe=exe,+ working_dir=working_dir,+ args=args,+ envs=envs,+ launch_detached=True,+ )+ result = backend.run_command(command, timeout=120)+ result["tool_mode"] = "unified"+ result["activity"] = activity+ return result+++def attach(+ *,+ nsight_path: str | None,+ activity: str,+ pid: int,+ project: str | None,+ output_dir: str | None,+ hostname: str | None,+ platform_name: str | None,+) -> dict:+ """Attach an activity to a running PID."""+ report = backend.probe_installation(nsight_path=nsight_path)+ binaries = report["binaries"]+ backend.require_binary(binaries, "ngfx")++ command = backend.build_unified_command(+ binaries,+ activity=activity,+ project=project,+ output_dir=output_dir,+ hostname=hostname,+ platform_name=platform_name,+ attach_pid=pid,+ )+ result = backend.run_command(command, timeout=120)+ result["tool_mode"] = "unified"+ result["activity"] = activity+ result["pid"] = pid+ return resultdiff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/nsight_graphics_cli.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/nsight_graphics_cli.pynew file mode 100644index 000000000..127d38e1e--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/nsight_graphics_cli.py@@ -0,0 +1,397 @@+#!/usr/bin/env python3+"""CLI harness for NVIDIA Nsight Graphics orchestration."""++from __future__ import annotations++import json+import os+import shlex++import click++from cli_anything.nsight_graphics.core import cpp_capture, doctor, frame, gpu_trace, launch++_repl_mode = False+++def _output(ctx: click.Context, data, human_fn=None):+ if ctx.obj.get("json_mode"):+ from cli_anything.nsight_graphics.utils.output import output_json++ output_json(data)+ elif human_fn:+ human_fn(data)+ else:+ from cli_anything.nsight_graphics.utils.output import output_json++ output_json(data)+++def _handle_exc(ctx: click.Context, exc: Exception):+ from cli_anything.nsight_graphics.utils.errors import handle_error++ payload = handle_error(exc, debug=ctx.obj.get("debug", False))+ if ctx.obj.get("json_mode"):+ from cli_anything.nsight_graphics.utils.output import output_json++ output_json(payload)+ ctx.exit(1)+ raise click.ClickException(payload["error"])+++def _common_kwargs(ctx: click.Context) -> dict:+ return {+ "nsight_path": ctx.obj.get("nsight_path"),+ "project": ctx.obj.get("project"),+ "output_dir": ctx.obj.get("output_dir"),+ "hostname": ctx.obj.get("hostname"),+ "platform_name": ctx.obj.get("platform_name"),+ }++[email protected](invoke_without_command=True)[email protected]("--json", "json_mode", is_flag=True, help="Output in JSON format.")[email protected]("--debug", is_flag=True, help="Show debug tracebacks on errors.")[email protected]("--nsight-path", type=click.Path(exists=False), default=None, help="Explicit Nsight Graphics install dir or executable.")[email protected]("--project", type=click.Path(exists=False), default=None, help="Nsight Graphics project file.")[email protected]("--output-dir", type=click.Path(exists=False), default=None, help="Output directory for captures or exports.")[email protected]("--hostname", default=None, help="Remote host name.")[email protected]("--platform", "platform_name", default=None, help="Target platform string.")[email protected]_option(package_name="cli-anything-nsight-graphics")[email protected]_context+def cli(ctx, json_mode, debug, nsight_path, project, output_dir, hostname, platform_name):+ """Nsight Graphics CLI - orchestration wrapper for official tools."""+ ctx.ensure_object(dict)+ ctx.obj["json_mode"] = json_mode+ ctx.obj["debug"] = debug+ if nsight_path is not None:+ ctx.obj["nsight_path"] = nsight_path+ if project is not None:+ ctx.obj["project"] = project+ if output_dir is not None:+ ctx.obj["output_dir"] = output_dir+ if hostname is not None:+ ctx.obj["hostname"] = hostname+ if platform_name is not None:+ ctx.obj["platform_name"] = platform_name+ if ctx.invoked_subcommand is None:+ ctx.invoke(repl)++[email protected]("doctor")+def doctor_group():+ """Installation and environment diagnostics."""+++@doctor_group.command("info")[email protected]_context+def doctor_info(ctx):+ """Show installation details and detected capabilities."""+ try:+ data = doctor.get_installation_report(nsight_path=ctx.obj.get("nsight_path"))++ def _human(report):+ click.echo(f"Mode: {report['compatibility_mode']}")+ click.echo(f"Version: {report.get('version') or 'unknown'}")+ click.echo(f"Primary: {report.get('resolved_executable') or 'not found'}")+ click.echo(f"Windows: {'yes' if report.get('verified_host') else 'unverified'}")+ if report.get("supported_activities"):+ click.echo("Activities:")+ for activity in report["supported_activities"]:+ click.echo(f" - {activity}")+ if report.get("warnings"):+ click.echo("Warnings:")+ for warning in report["warnings"]:+ click.echo(f" - {warning}")++ _output(ctx, data, _human)+ except Exception as exc:+ _handle_exc(ctx, exc)+++@doctor_group.command("versions")[email protected]_context+def doctor_versions(ctx):+ """List detected Nsight Graphics installations and versions."""+ try:+ data = doctor.list_installations(nsight_path=ctx.obj.get("nsight_path"))++ def _human(report):+ click.echo(f"Found: {report['count']}")+ if report.get("selected_executable"):+ click.echo(f"Selected: {report['selected_executable']}")+ for item in report.get("installations", []):+ marker = "*" if item.get("selected") else " "+ version = item.get("version") or "unknown"+ sources = "+".join(item.get("discovery_sources", []))+ click.echo(f"{marker} {version} [{item['tool_mode']}] ({sources})")+ if item.get("display_name"):+ click.echo(f" {item['display_name']}")+ if item.get("install_root"):+ click.echo(f" {item['install_root']}")+ elif item.get("registry_key"):+ click.echo(f" {item['registry_key']}")+ if item.get("install_source") and item.get("registered_only"):+ click.echo(f" source: {item['install_source']}")++ _output(ctx, data, _human)+ except Exception as exc:+ _handle_exc(ctx, exc)++[email protected]("launch")+def launch_group():+ """Launch or attach targets under Nsight Graphics."""+++@launch_group.command("detached")[email protected]("--activity", default="Frame Debugger", show_default=True, help="Nsight activity name.")[email protected]("--exe", "exe_path", type=click.Path(exists=False), default=None, help="Target executable path.")[email protected]("--dir", "working_dir", type=click.Path(exists=False), default=None, help="Target working directory.")[email protected]("--arg", "program_args", multiple=True, help="Target argument. Repeat for multiple.")[email protected]("--env", "envs", multiple=True, help="Environment entry KEY=VALUE.")[email protected]_context+def launch_detached_cmd(ctx, activity, exe_path, working_dir, program_args, envs):+ """Launch a target under Nsight and return immediately."""+ try:+ data = launch.launch_detached(+ activity=activity,+ exe=exe_path,+ working_dir=working_dir,+ args=program_args,+ envs=envs,+ **_common_kwargs(ctx),+ )+ _output(ctx, data)+ except Exception as exc:+ _handle_exc(ctx, exc)+++@launch_group.command("attach")[email protected]("--activity", default="Frame Debugger", show_default=True, help="Nsight activity name.")[email protected]("--pid", type=int, required=True, help="PID to attach.")[email protected]_context+def launch_attach_cmd(ctx, activity, pid):+ """Attach an Nsight activity to a running PID."""+ try:+ data = launch.attach(+ activity=activity,+ pid=pid,+ **_common_kwargs(ctx),+ )+ _output(ctx, data)+ except Exception as exc:+ _handle_exc(ctx, exc)++[email protected]("frame")+def frame_group():+ """Frame Debugger capture commands."""+++@frame_group.command("capture")[email protected]("--exe", "exe_path", type=click.Path(exists=False), default=None, help="Target executable path.")[email protected]("--dir", "working_dir", type=click.Path(exists=False), default=None, help="Target working directory.")[email protected]("--arg", "program_args", multiple=True, help="Target argument. Repeat for multiple.")[email protected]("--env", "envs", multiple=True, help="Environment entry KEY=VALUE.")[email protected]("--wait-seconds", type=int, default=None, help="Wait N seconds before capture.")[email protected]("--wait-frames", type=int, default=None, help="Wait N frames before capture.")[email protected]("--wait-hotkey", is_flag=True, help="Wait for the target capture hotkey.")[email protected]("--export-frame-perf-metrics", is_flag=True, help="Export whole-frame performance metrics.")[email protected]("--export-range-perf-metrics", is_flag=True, help="Export per-range performance metrics.")[email protected]_context+def frame_capture_cmd(+ ctx,+ exe_path,+ working_dir,+ program_args,+ envs,+ wait_seconds,+ wait_frames,+ wait_hotkey,+ export_frame_perf_metrics,+ export_range_perf_metrics,+):+ """Run a Frame Debugger capture."""+ try:+ data = frame.capture_frame(+ exe=exe_path,+ working_dir=working_dir,+ args=program_args,+ envs=envs,+ wait_seconds=wait_seconds,+ wait_frames=wait_frames,+ wait_hotkey=wait_hotkey,+ export_frame_perf_metrics=export_frame_perf_metrics,+ export_range_perf_metrics=export_range_perf_metrics,+ **_common_kwargs(ctx),+ )+ _output(ctx, data)+ except Exception as exc:+ _handle_exc(ctx, exc)++[email protected]("gpu-trace")+def gpu_trace_group():+ """GPU Trace capture commands."""+++@gpu_trace_group.command("capture")[email protected]("--exe", "exe_path", type=click.Path(exists=False), default=None, help="Target executable path.")[email protected]("--dir", "working_dir", type=click.Path(exists=False), default=None, help="Target working directory.")[email protected]("--arg", "program_args", multiple=True, help="Target argument. Repeat for multiple.")[email protected]("--env", "envs", multiple=True, help="Environment entry KEY=VALUE.")[email protected]("--start-after-frames", type=int, default=None, help="Wait N frames before trace.")[email protected]("--start-after-submits", type=int, default=None, help="Wait N submits before trace.")[email protected]("--start-after-ms", type=int, default=None, help="Wait N milliseconds before trace.")[email protected]("--start-after-hotkey", is_flag=True, help="Wait for the target capture hotkey.")[email protected]("--max-duration-ms", type=int, default=None, help="Maximum trace duration.")[email protected]("--limit-to-frames", type=int, default=None, help="Trace at most N frames.")[email protected]("--limit-to-submits", type=int, default=None, help="Trace at most N submits.")[email protected]("--auto-export", is_flag=True, help="Automatically export metrics data.")[email protected]("--architecture", default=None, help="Architecture name.")[email protected]("--metric-set-id", default=None, help="Metric set id for the selected architecture.")[email protected]("--multi-pass-metrics", is_flag=True, help="Enable multi-pass metrics.")[email protected]("--real-time-shader-profiler", is_flag=True, help="Enable real-time shader profiler.")[email protected]_context+def gpu_trace_capture_cmd(+ ctx,+ exe_path,+ working_dir,+ program_args,+ envs,+ start_after_frames,+ start_after_submits,+ start_after_ms,+ start_after_hotkey,+ max_duration_ms,+ limit_to_frames,+ limit_to_submits,+ auto_export,+ architecture,+ metric_set_id,+ multi_pass_metrics,+ real_time_shader_profiler,+):+ """Run a GPU Trace capture."""+ try:+ data = gpu_trace.capture_trace(+ exe=exe_path,+ working_dir=working_dir,+ args=program_args,+ envs=envs,+ start_after_frames=start_after_frames,+ start_after_submits=start_after_submits,+ start_after_ms=start_after_ms,+ start_after_hotkey=start_after_hotkey,+ max_duration_ms=max_duration_ms,+ limit_to_frames=limit_to_frames,+ limit_to_submits=limit_to_submits,+ auto_export=auto_export,+ architecture=architecture,+ metric_set_id=metric_set_id,+ multi_pass_metrics=multi_pass_metrics,+ real_time_shader_profiler=real_time_shader_profiler,+ **_common_kwargs(ctx),+ )+ _output(ctx, data)+ except Exception as exc:+ _handle_exc(ctx, exc)++[email protected]("cpp")+def cpp_group():+ """Generate C++ Capture commands."""+++@cpp_group.command("capture")[email protected]("--exe", "exe_path", type=click.Path(exists=False), default=None, help="Target executable path.")[email protected]("--dir", "working_dir", type=click.Path(exists=False), default=None, help="Target working directory.")[email protected]("--arg", "program_args", multiple=True, help="Target argument. Repeat for multiple.")[email protected]("--env", "envs", multiple=True, help="Environment entry KEY=VALUE.")[email protected]("--wait-seconds", type=int, default=None, help="Wait N seconds before capture.")[email protected]("--wait-hotkey", is_flag=True, help="Wait for the target capture hotkey.")[email protected]_context+def cpp_capture_cmd(ctx, exe_path, working_dir, program_args, envs, wait_seconds, wait_hotkey):+ """Run Generate C++ Capture."""+ try:+ data = cpp_capture.capture_cpp(+ exe=exe_path,+ working_dir=working_dir,+ args=program_args,+ envs=envs,+ wait_seconds=wait_seconds,+ wait_hotkey=wait_hotkey,+ **_common_kwargs(ctx),+ )+ _output(ctx, data)+ except Exception as exc:+ _handle_exc(ctx, exc)++[email protected]_context+def repl(ctx):+ """Start the interactive REPL."""+ from cli_anything.nsight_graphics.utils.repl_skin import ReplSkin++ global _repl_mode+ _repl_mode = True++ skin = ReplSkin("nsight-graphics", version="0.1.0")+ skin.print_banner()+ session = skin.create_prompt_session()++ commands = {+ "doctor": "info|versions",+ "launch": "detached|attach",+ "frame": "capture",+ "gpu-trace": "capture",+ "cpp": "capture",+ "help": "Show this help",+ "quit": "Exit REPL",+ }++ try:+ while True:+ try:+ context = os.path.basename(ctx.obj.get("project", "")) if ctx.obj.get("project") else ""+ line = skin.get_input(session, project_name=context, modified=False)+ if not line:+ continue+ if line.lower() in ("quit", "exit", "q"):+ skin.print_goodbye()+ break+ if line.lower() == "help":+ skin.help(commands)+ continue++ args = shlex.split(line, posix=os.name != "nt")+ if ctx.obj.get("json_mode"):+ args = ["--json", *args]+ if ctx.obj.get("debug"):+ args = ["--debug", *args]+ try:+ cli.main(args, standalone_mode=False, obj=ctx.obj)+ except SystemExit:+ pass+ except click.exceptions.UsageError as exc:+ skin.warning(f"Usage error: {exc}")+ except Exception as exc:+ if ctx.obj.get("json_mode"):+ click.echo(json.dumps({"error": str(exc)}, indent=2))+ else:+ skin.error(str(exc))+ except (EOFError, KeyboardInterrupt):+ skin.print_goodbye()+ break+ finally:+ _repl_mode = False+++def main():+ cli(obj={})+++if __name__ == "__main__":+ main()diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/skills/SKILL.md b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/skills/SKILL.mdnew file mode 100644index 000000000..6fbb3c0de--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/skills/SKILL.md@@ -0,0 +1,82 @@+---+name: cli-anything-nsight-graphics+description: Windows-first CLI harness for Nsight Graphics launch, frame capture, GPU Trace, and C++ Capture orchestration+version: 0.1.0+command: cli-anything-nsight-graphics+install: pip install cli-anything-nsight-graphics+requires:+ - NVIDIA Nsight Graphics installation+ - Windows host recommended+categories:+ - graphics+ - debugging+ - gpu+ - profiling+---++# Nsight Graphics CLI Skill++Command-line orchestration of official NVIDIA Nsight Graphics activities.++## Capabilities++- Probe installed Nsight binaries and compatibility mode+- Launch an application detached under Nsight+- Attach Nsight to a running PID+- Trigger Frame Debugger capture+- Trigger GPU Trace capture and auto-export+- Trigger Generate C++ Capture++## Commands++### doctor++```bash+cli-anything-nsight-graphics --json doctor info+cli-anything-nsight-graphics --json doctor versions+cli-anything-nsight-graphics --nsight-path "C:\Path\To\Nsight Graphics 2024.2\host\windows-desktop-nomad-x64" --json doctor info+```++### launch++```bash+cli-anything-nsight-graphics launch detached --activity "Frame Debugger" --exe "C:\Path\To\App.exe"+cli-anything-nsight-graphics launch attach --activity "Frame Debugger" --pid 12345+```++### frame capture++```bash+cli-anything-nsight-graphics --output-dir D:\captures frame capture ^+ --exe "C:\Path\To\App.exe" ^+ --wait-frames 10+```++### GPU Trace++```bash+cli-anything-nsight-graphics --output-dir D:\traces gpu-trace capture ^+ --exe "C:\Path\To\App.exe" ^+ --start-after-ms 1000 ^+ --limit-to-frames 1 ^+ --auto-export+```++### Generate C++ Capture++```bash+cli-anything-nsight-graphics --output-dir D:\cpp cpp capture ^+ --exe "C:\Path\To\App.exe" ^+ --wait-seconds 5+```++## Agent Notes++- Prefer `doctor info` first to discover the available compatibility mode.+- Use `doctor versions` to list detected installs when multiple Nsight Graphics versions exist.+- Use `--nsight-path` to force a specific install directory or `ngfx.exe`.+- Use `--json` for programmatic workflows.+- Frame/GPU/C++ capture commands require a launch target through `--exe` or a+ preconfigured root-level `--project`.+- V1 is orchestration-focused; it does not expose shader, pipeline, or resource+ inspection commands.diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/TEST.md b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/TEST.mdnew file mode 100644index 000000000..31677e193--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/TEST.md@@ -0,0 +1,115 @@+# TEST.md β Nsight Graphics CLI Test Plan & Results++## Test Inventory Plan++- `test_core.py`: 28 unit tests planned+- `test_full_e2e.py`: 4 E2E tests planned++## Unit Test Plan++### `utils/nsight_graphics_backend.py`++- executable discovery from env override and install directories+- compatibility mode detection+- CLI override precedence via `--nsight-path`+- `ngfx --help-all` parsing for activities and options+- installation listing and version reporting+- Windows registry discovery for registered-only installs+- fixed-drive discovery for non-`C:` installs+- unified and split command construction+- artifact diffing behavior++### `core/*.py`++- frame capture command routing+- split-mode fallback restrictions+- GPU Trace validation for trigger/limit options+- launch attach/detached wrapping++### `nsight_graphics_cli.py`++- root help+- help for `doctor`, `launch`, `frame`, `gpu-trace`, and `cpp`+- subprocess smoke test via `python -m`++## E2E Test Plan++Environment prerequisites:++- Nsight Graphics installed and discoverable+- `NSIGHT_GRAPHICS_TEST_EXE`+- optional `NSIGHT_GRAPHICS_TEST_ARGS`+- optional `NSIGHT_GRAPHICS_TEST_WORKDIR`++Scenarios:++1. `doctor info` returns installation metadata+2. `frame capture` produces one or more non-empty artifacts+3. `gpu-trace capture --auto-export` produces one or more non-empty artifacts+4. `cpp capture` produces one or more non-empty artifacts++## Running Tests++```bash+cd nsight-graphics/agent-harness+python -m pip install -e .+python -m pytest cli_anything/nsight_graphics/tests -v --tb=no+```++## Test Results++```text+============================= test session starts =============================+platform win32 -- Python 3.11.9, pytest-9.0.3, pluggy-1.6.0 -- C:\Users\aimidi\AppData\Local\Programs\Python\Python311\python.exe+cachedir: .pytest_cache+rootdir: D:\code\D5\CLI-Anything-nsight-graphics\nsight-graphics\agent-harness+collecting ... collected 32 items++cli_anything/nsight_graphics/tests/test_core.py::TestOutputAndErrors::test_output_json PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestOutputAndErrors::test_handle_error_debug PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_default_windows_install_dirs_prefers_higher_version PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_discover_binaries_from_env_dir PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_discover_binaries_prefers_cli_override PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_detect_tool_mode PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_list_installations_reports_versions PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_list_installations_includes_registry_only_entries PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_list_installations_merges_registry_metadata_into_filesystem_entry PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestBackendDiscovery::test_list_installations_promotes_newer_drive_install PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestHelpParsing::test_parse_unified_help_extracts_activities_and_options PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCommandBuilders::test_build_unified_command_formats_args_and_env PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCommandBuilders::test_build_split_capture_command_maps_wait_seconds PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCommandBuilders::test_diff_snapshots_reports_new_nonempty_files PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_frame_capture_uses_unified_ngfx PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_frame_capture_split_mode_rejects_perf_exports PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_gpu_trace_requires_arch_for_metric_set PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_launch_attach_returns_unified_result PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCoreModules::test_cpp_capture_sets_activity PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_root_help PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_nsight_path_is_forwarded_to_doctor PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args0-info] PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args1-versions] PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args2-detached] PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args3-capture] PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args4-capture] PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCLIHelp::test_group_help[args5-capture] PASSED+cli_anything/nsight_graphics/tests/test_core.py::TestCLISubprocess::test_cli_help_subprocess PASSED+cli_anything/nsight_graphics/tests/test_full_e2e.py::TestDoctorE2E::test_doctor_info PASSED+cli_anything/nsight_graphics/tests/test_full_e2e.py::TestTargetedE2E::test_frame_capture SKIPPED+cli_anything/nsight_graphics/tests/test_full_e2e.py::TestTargetedE2E::test_gpu_trace_capture SKIPPED+cli_anything/nsight_graphics/tests/test_full_e2e.py::TestTargetedE2E::test_cpp_capture SKIPPED++======================== 29 passed, 3 skipped in 1.83s ========================+```++## Summary Statistics++- Total tests collected: 32+- Passed: 29+- Skipped: 3+- Pass rate for executed tests: 100%++## Coverage Notes++- `doctor info` E2E passed against the local Nsight Graphics installation.+- Target-dependent E2E scenarios are implemented but currently skipped until+ `NSIGHT_GRAPHICS_TEST_EXE` (and optional args/workdir) are provided.diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/__init__.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/__init__.pynew file mode 100644index 000000000..2dedd3962--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/__init__.py@@ -0,0 +1 @@+"""Tests for cli-anything-nsight-graphics."""diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_core.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_core.pynew file mode 100644index 000000000..c3c21f2c1--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_core.py@@ -0,0 +1,505 @@+"""Unit tests for cli-anything-nsight-graphics."""++from __future__ import annotations++import io+import json+import os+import subprocess+import sys+from pathlib import Path+from unittest.mock import patch++import pytest++from cli_anything.nsight_graphics.core import cpp_capture, frame, gpu_trace, launch+from cli_anything.nsight_graphics.utils import nsight_graphics_backend as backend+from cli_anything.nsight_graphics.utils.errors import handle_error+from cli_anything.nsight_graphics.utils.output import output_json++SAMPLE_HELP = """+NVIDIA Nsight Graphics [general_options] [activity_options]:++General Options:+ --hostname arg Host name of remote connection+ --project arg Nsight project file to load+ --output-dir arg Output folder to export/write data to+ --activity arg Target activity to use, should be one of:+ Frame Debugger+ Generate C++ Capture+ GPU Trace Profiler+ --platform arg Target platform to use, should be one of:+ Windows+ --launch-detached Run as a command line launcher+ --attach-pid arg PID to connect to+ --exe arg Executable path to be launched with the tool injected+ --dir arg Working directory of launched application+ --args arg Command-line arguments of launched application+ --env arg Environment variables of launched application++Frame Debugger activity options:+ --wait-frames arg Wait in frames before capturing a frame+ --wait-seconds arg Wait in time (seconds) before capturing a frame+ --wait-hotkey Wait for hotkey+ --export-frame-perf-metrics Export metrics++Generate C++ Capture activity options:+ --wait-seconds arg Wait in time (seconds) before capturing a frame+ --wait-hotkey Wait for hotkey++GPU Trace Profiler activity options:+ --start-after-frames arg Wait N frames before generating GPU trace+ --start-after-ms arg Wait N milliseconds before generating GPU trace+ --limit-to-frames arg Trace a maximum of N frames+ --auto-export Automatically export metrics data after generating GPU trace+ --architecture arg Selects which architecture the options configure+ --metric-set-id arg Metric set id+ --multi-pass-metrics Enable multi-pass metrics+ --real-time-shader-profiler Enable shader profiler+"""+++class TestOutputAndErrors:+ def test_output_json(self):+ buffer = io.StringIO()+ output_json({"key": "value", "num": 42}, file=buffer)+ payload = json.loads(buffer.getvalue())+ assert payload["key"] == "value"+ assert payload["num"] == 42++ def test_handle_error_debug(self):+ try:+ raise RuntimeError("boom")+ except RuntimeError as exc:+ payload = handle_error(exc, debug=True)+ assert payload["type"] == "RuntimeError"+ assert "traceback" in payload+++class TestBackendDiscovery:+ def test_default_windows_install_dirs_prefers_higher_version(self):+ with patch("cli_anything.nsight_graphics.utils.nsight_graphics_backend._fixed_windows_drive_roots", return_value=["C:", "D:"]):+ result = backend._default_windows_install_dirs(+ lambda pattern: {+ "C:/Program Files/NVIDIA Corporation/Nsight Graphics */host/windows-desktop-nomad-x64": [+ "C:/Program Files/NVIDIA Corporation/Nsight Graphics 2023.3.2/host/windows-desktop-nomad-x64"+ ],+ "D:/Program Files/NVIDIA Corporation/Nsight Graphics */host/windows-desktop-nomad-x64": [+ "D:/Program Files/NVIDIA Corporation/Nsight Graphics 2026.1.0/host/windows-desktop-nomad-x64"+ ],+ "C:/Program Files (x86)/NVIDIA Corporation/Nsight Graphics */host/windows-desktop-nomad-x64": [],+ "D:/Program Files (x86)/NVIDIA Corporation/Nsight Graphics */host/windows-desktop-nomad-x64": [],+ }.get(pattern, [])+ )+ assert result[0].startswith("D:/Program Files")++ def test_discover_binaries_from_env_dir(self, tmp_path):+ (tmp_path / "ngfx.exe").write_text("", encoding="utf-8")+ (tmp_path / "ngfx-capture.exe").write_text("", encoding="utf-8")++ result = backend.discover_binaries(+ env={backend.ENV_VAR: str(tmp_path)},+ which=lambda _: None,+ glob_func=lambda _: [],+ platform_system="Windows",+ )++ assert result["binaries"]["ngfx"].endswith("ngfx.exe")+ assert result["binaries"]["ngfx_capture"].endswith("ngfx-capture.exe")+ assert result["effective_override"] == str(tmp_path)++ def test_discover_binaries_prefers_cli_override(self, tmp_path):+ (tmp_path / "ngfx.exe").write_text("", encoding="utf-8")+ result = backend.discover_binaries(+ env={backend.ENV_VAR: "C:/Ignored/FromEnv"},+ nsight_path=str(tmp_path),+ which=lambda _: None,+ glob_func=lambda _: [],+ platform_system="Windows",+ )+ assert result["cli_override"] == str(tmp_path)+ assert result["effective_override"] == str(tmp_path)+ assert result["binaries"]["ngfx"].endswith("ngfx.exe")++ def test_detect_tool_mode(self):+ assert backend.detect_tool_mode({"ngfx": "a", "ngfx_capture": None, "ngfx_replay": None}) == "unified"+ assert backend.detect_tool_mode({"ngfx": None, "ngfx_capture": "a", "ngfx_replay": None}) == "split"+ assert backend.detect_tool_mode({"ngfx": None, "ngfx_capture": None, "ngfx_replay": None}) == "missing"++ def test_list_installations_reports_versions(self, tmp_path):+ install_dir = tmp_path / "Nsight Graphics 2025.1" / "host" / "windows-desktop-nomad-x64"+ install_dir.mkdir(parents=True)+ (install_dir / "ngfx.exe").write_text("", encoding="utf-8")+ (install_dir / "ngfx-ui.exe").write_text("", encoding="utf-8")++ with patch("cli_anything.nsight_graphics.utils.nsight_graphics_backend._read_registry_installations", return_value=[]):+ result = backend.list_installations(+ env={},+ nsight_path=str(install_dir),+ which=lambda _: None,+ glob_func=lambda _: [str(install_dir)],+ platform_system="Windows",+ )++ assert result["count"] == 1+ assert result["installations"][0]["version"] == "2025.1"+ assert result["installations"][0]["selected"] is True++ def test_list_installations_includes_registry_only_entries(self):+ registry_entries = [+ {+ "display_name": "NVIDIA Nsight Graphics 2026.1.0",+ "display_version": "26.1.26068.0509",+ "install_location": None,+ "install_source": "C:/Users/Test/Downloads",+ "uninstall_string": "msiexec /x ...",+ "publisher": "NVIDIA Corporation",+ "registry_key": r"HKLM\SOFTWARE\...\{ABC}",+ }+ ]+ with patch("cli_anything.nsight_graphics.utils.nsight_graphics_backend._read_registry_installations", return_value=registry_entries):+ result = backend.list_installations(+ env={},+ which=lambda _: None,+ glob_func=lambda _: [],+ platform_system="Windows",+ )++ assert result["count"] == 1+ assert result["registry_count"] == 1+ assert result["installations"][0]["version"] == "2026.1.0"+ assert result["installations"][0]["registered_only"] is True+ assert result["installations"][0]["tool_mode"] == "registered-only"++ def test_list_installations_merges_registry_metadata_into_filesystem_entry(self, tmp_path):+ install_dir = tmp_path / "Nsight Graphics 2025.1" / "host" / "windows-desktop-nomad-x64"+ install_dir.mkdir(parents=True)+ (install_dir / "ngfx.exe").write_text("", encoding="utf-8")++ registry_entries = [+ {+ "display_name": "NVIDIA Nsight Graphics 2025.1",+ "display_version": "25.1.0",+ "install_location": str(install_dir),+ "install_source": "C:/Installers",+ "uninstall_string": "msiexec /x ...",+ "publisher": "NVIDIA Corporation",+ "registry_key": r"HKLM\SOFTWARE\...\{DEF}",+ }+ ]+ with patch("cli_anything.nsight_graphics.utils.nsight_graphics_backend._read_registry_installations", return_value=registry_entries):+ result = backend.list_installations(+ env={},+ nsight_path=str(install_dir),+ which=lambda _: None,+ glob_func=lambda _: [str(install_dir)],+ platform_system="Windows",+ )++ assert result["count"] == 1+ assert result["registry_count"] == 1+ assert result["installations"][0]["registered_only"] is False+ assert result["installations"][0]["display_name"] == "NVIDIA Nsight Graphics 2025.1"+ assert "registry" in result["installations"][0]["discovery_sources"]++ def test_list_installations_promotes_newer_drive_install(self, tmp_path):+ c_dir = tmp_path / "CDrive" / "Nsight Graphics 2023.3.2" / "host" / "windows-desktop-nomad-x64"+ d_dir = tmp_path / "DDrive" / "Nsight Graphics 2026.1.0" / "host" / "windows-desktop-nomad-x64"+ c_dir.mkdir(parents=True)+ d_dir.mkdir(parents=True)+ (c_dir / "ngfx.exe").write_text("", encoding="utf-8")+ (d_dir / "ngfx.exe").write_text("", encoding="utf-8")++ with patch("cli_anything.nsight_graphics.utils.nsight_graphics_backend._fixed_windows_drive_roots", return_value=["C:", "D:"]), \+ patch("cli_anything.nsight_graphics.utils.nsight_graphics_backend._read_registry_installations", return_value=[]):+ result = backend.list_installations(+ env={},+ which=lambda _: None,+ glob_func=lambda pattern: {+ "C:/Program Files/NVIDIA Corporation/Nsight Graphics */host/windows-desktop-nomad-x64": [str(c_dir).replace("\\", "/")],+ "D:/Program Files/NVIDIA Corporation/Nsight Graphics */host/windows-desktop-nomad-x64": [str(d_dir).replace("\\", "/")],+ "C:/Program Files (x86)/NVIDIA Corporation/Nsight Graphics */host/windows-desktop-nomad-x64": [],+ "D:/Program Files (x86)/NVIDIA Corporation/Nsight Graphics */host/windows-desktop-nomad-x64": [],+ }.get(pattern, []),+ platform_system="Windows",+ )++ assert result["installations"][0]["version"] == "2026.1.0"+++class TestHelpParsing:+ def test_parse_unified_help_extracts_activities_and_options(self):+ result = backend.parse_unified_help(SAMPLE_HELP)+ assert result["activities"] == [+ "Frame Debugger",+ "Generate C++ Capture",+ "GPU Trace Profiler",+ ]+ assert result["platforms"] == ["Windows"]+ assert "--project" in result["general_options"]+ assert "--wait-frames" in result["activity_options"]["Frame Debugger"]+ assert "--metric-set-id" in result["activity_options"]["GPU Trace Profiler"]+++class TestCommandBuilders:+ def test_build_unified_command_formats_args_and_env(self):+ command = backend.build_unified_command(+ {"ngfx": "C:/Nsight/ngfx.exe"},+ activity="Frame Debugger",+ project="demo.ngfx-proj",+ output_dir="D:/out",+ hostname="localhost",+ platform_name="Windows",+ exe="C:/demo.exe",+ working_dir="C:/demo",+ args=["--flag", "value with spaces"],+ envs=["A=1", "B=two"],+ launch_detached=True,+ extra_args=["--wait-frames", "10"],+ )+ assert command[0] == "C:/Nsight/ngfx.exe"+ assert "--launch-detached" in command+ assert "--args" in command+ assert "--env" in command+ assert "value with spaces" in command[command.index("--args") + 1]+ assert command[command.index("--env") + 1].endswith(";")++ def test_build_split_capture_command_maps_wait_seconds(self):+ command = backend.build_split_capture_command(+ {"ngfx_capture": "C:/Nsight/ngfx-capture.exe"},+ exe="C:/demo.exe",+ wait_seconds=3,+ wait_frames=None,+ wait_hotkey=False,+ )+ assert command[0] == "C:/Nsight/ngfx-capture.exe"+ assert "--capture-countdown-timer" in command+ assert command[command.index("--capture-countdown-timer") + 1] == "3000"++ def test_diff_snapshots_reports_new_nonempty_files(self, tmp_path):+ before = backend.snapshot_files([str(tmp_path)])+ artifact = tmp_path / "capture.ngfx-capture"+ artifact.write_text("data", encoding="utf-8")+ after = backend.snapshot_files([str(tmp_path)])+ diff = backend.diff_snapshots(before, after)+ assert len(diff) == 1+ assert diff[0]["path"].endswith("capture.ngfx-capture")+ assert diff[0]["size"] > 0+++class TestCoreModules:+ @patch("cli_anything.nsight_graphics.core.frame.backend.run_with_artifacts")+ @patch("cli_anything.nsight_graphics.core.frame.backend.build_unified_command")+ @patch("cli_anything.nsight_graphics.core.frame.backend.probe_installation")+ def test_frame_capture_uses_unified_ngfx(self, probe_mock, build_mock, run_mock):+ probe_mock.return_value = {+ "binaries": {"ngfx": "C:/Nsight/ngfx.exe", "ngfx_capture": None, "ngfx_replay": None},+ }+ build_mock.return_value = ["C:/Nsight/ngfx.exe", "--activity", "Frame Debugger"]+ run_mock.return_value = {+ "ok": True,+ "returncode": 0,+ "stdout": "",+ "stderr": "",+ "command": "ngfx",+ "artifacts": [{"path": "D:/out/capture.ngfx-capture", "size": 10, "mtime_ns": 1}],+ }++ result = frame.capture_frame(+ nsight_path=None,+ project=None,+ output_dir="D:/out",+ hostname=None,+ platform_name=None,+ exe="C:/demo.exe",+ working_dir=None,+ args=(),+ envs=(),+ wait_seconds=None,+ wait_frames=10,+ wait_hotkey=False,+ export_frame_perf_metrics=False,+ export_range_perf_metrics=False,+ )++ assert build_mock.called+ assert result["tool_mode"] == "unified"+ assert result["activity"] == "Frame Debugger"+ assert result["artifacts"]++ @patch("cli_anything.nsight_graphics.core.frame.backend.probe_installation")+ def test_frame_capture_split_mode_rejects_perf_exports(self, probe_mock):+ probe_mock.return_value = {+ "binaries": {"ngfx": None, "ngfx_capture": "C:/Nsight/ngfx-capture.exe", "ngfx_replay": None},+ }+ with pytest.raises(RuntimeError, match="Frame performance export flags"):+ frame.capture_frame(+ nsight_path=None,+ project=None,+ output_dir=None,+ hostname=None,+ platform_name=None,+ exe="C:/demo.exe",+ working_dir=None,+ args=(),+ envs=(),+ wait_seconds=None,+ wait_frames=1,+ wait_hotkey=False,+ export_frame_perf_metrics=True,+ export_range_perf_metrics=False,+ )++ @patch("cli_anything.nsight_graphics.core.gpu_trace.backend.probe_installation")+ def test_gpu_trace_requires_arch_for_metric_set(self, probe_mock):+ probe_mock.return_value = {+ "binaries": {"ngfx": "C:/Nsight/ngfx.exe", "ngfx_capture": None, "ngfx_replay": None},+ }+ with pytest.raises(ValueError, match="requires --architecture"):+ gpu_trace.capture_trace(+ nsight_path=None,+ project=None,+ output_dir=None,+ hostname=None,+ platform_name=None,+ exe="C:/demo.exe",+ working_dir=None,+ args=(),+ envs=(),+ start_after_frames=1,+ start_after_submits=None,+ start_after_ms=None,+ start_after_hotkey=False,+ max_duration_ms=None,+ limit_to_frames=1,+ limit_to_submits=None,+ auto_export=False,+ architecture=None,+ metric_set_id="1",+ multi_pass_metrics=False,+ real_time_shader_profiler=False,+ )++ @patch("cli_anything.nsight_graphics.core.launch.backend.run_command")+ @patch("cli_anything.nsight_graphics.core.launch.backend.build_unified_command")+ @patch("cli_anything.nsight_graphics.core.launch.backend.probe_installation")+ def test_launch_attach_returns_unified_result(self, probe_mock, build_mock, run_mock):+ probe_mock.return_value = {+ "binaries": {"ngfx": "C:/Nsight/ngfx.exe", "ngfx_capture": None, "ngfx_replay": None},+ }+ build_mock.return_value = ["C:/Nsight/ngfx.exe", "--attach-pid", "123"]+ run_mock.return_value = {+ "ok": True,+ "returncode": 0,+ "stdout": "",+ "stderr": "",+ "command": "ngfx",+ }++ result = launch.attach(+ nsight_path=None,+ activity="Frame Debugger",+ pid=123,+ project=None,+ output_dir=None,+ hostname=None,+ platform_name=None,+ )+ assert result["tool_mode"] == "unified"+ assert result["pid"] == 123++ @patch("cli_anything.nsight_graphics.core.cpp_capture.backend.run_with_artifacts")+ @patch("cli_anything.nsight_graphics.core.cpp_capture.backend.build_unified_command")+ @patch("cli_anything.nsight_graphics.core.cpp_capture.backend.probe_installation")+ def test_cpp_capture_sets_activity(self, probe_mock, build_mock, run_mock):+ probe_mock.return_value = {+ "binaries": {"ngfx": "C:/Nsight/ngfx.exe", "ngfx_capture": None, "ngfx_replay": None},+ }+ build_mock.return_value = ["C:/Nsight/ngfx.exe", "--activity", "Generate C++ Capture"]+ run_mock.return_value = {+ "ok": True,+ "returncode": 0,+ "stdout": "",+ "stderr": "",+ "command": "ngfx",+ "artifacts": [],+ }+ result = cpp_capture.capture_cpp(+ nsight_path=None,+ project=None,+ output_dir="D:/out",+ hostname=None,+ platform_name=None,+ exe="C:/demo.exe",+ working_dir=None,+ args=(),+ envs=(),+ wait_seconds=5,+ wait_hotkey=False,+ )+ assert result["activity"] == "Generate C++ Capture"+ assert result["tool_mode"] == "unified"+++class TestCLIHelp:+ def test_root_help(self):+ from click.testing import CliRunner+ from cli_anything.nsight_graphics.nsight_graphics_cli import cli++ runner = CliRunner()+ result = runner.invoke(cli, ["--help"])+ assert result.exit_code == 0+ assert "Nsight Graphics CLI" in result.output+ assert "--nsight-path" in result.output++ def test_nsight_path_is_forwarded_to_doctor(self):+ from click.testing import CliRunner+ from cli_anything.nsight_graphics.nsight_graphics_cli import cli++ runner = CliRunner()+ with patch("cli_anything.nsight_graphics.nsight_graphics_cli.doctor.get_installation_report") as doctor_mock:+ doctor_mock.return_value = {+ "ok": True,+ "compatibility_mode": "unified",+ "resolved_executable": "C:/Custom/ngfx.exe",+ "supported_activities": [],+ "warnings": [],+ }+ result = runner.invoke(cli, ["--json", "--nsight-path", "C:/Custom/NG", "doctor", "info"])++ assert result.exit_code == 0+ doctor_mock.assert_called_once_with(nsight_path="C:/Custom/NG")++ @pytest.mark.parametrize(+ ("args", "needle"),+ [+ (["doctor", "--help"], "info"),+ (["doctor", "--help"], "versions"),+ (["launch", "--help"], "detached"),+ (["frame", "--help"], "capture"),+ (["gpu-trace", "--help"], "capture"),+ (["cpp", "--help"], "capture"),+ ],+ )+ def test_group_help(self, args, needle):+ from click.testing import CliRunner+ from cli_anything.nsight_graphics.nsight_graphics_cli import cli++ runner = CliRunner()+ result = runner.invoke(cli, args)+ assert result.exit_code == 0+ assert needle in result.output+++class TestCLISubprocess:+ def test_cli_help_subprocess(self):+ harness_root = Path(__file__).resolve().parents[3]+ result = subprocess.run(+ [sys.executable, "-m", "cli_anything.nsight_graphics.nsight_graphics_cli", "--help"],+ capture_output=True,+ text=True,+ timeout=15,+ cwd=str(harness_root),+ )+ assert result.returncode == 0+ assert "Nsight Graphics CLI" in result.stdoutdiff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_full_e2e.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_full_e2e.pynew file mode 100644index 000000000..efe9a545a--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/tests/test_full_e2e.py@@ -0,0 +1,134 @@+"""Conditional end-to-end tests for cli-anything-nsight-graphics."""++from __future__ import annotations++import json+import os+import shlex+import shutil+import subprocess+import sys+from pathlib import Path++import pytest++from cli_anything.nsight_graphics.utils.nsight_graphics_backend import probe_installation++HARNESS_ROOT = str(Path(__file__).resolve().parents[3])+TEST_EXE = os.environ.get("NSIGHT_GRAPHICS_TEST_EXE", "").strip()+TEST_ARGS = os.environ.get("NSIGHT_GRAPHICS_TEST_ARGS", "").strip()+TEST_WORKDIR = os.environ.get("NSIGHT_GRAPHICS_TEST_WORKDIR", "").strip()+HAS_NSIGHT = bool(probe_installation().get("ok"))+HAS_TEST_EXE = bool(TEST_EXE and os.path.isfile(TEST_EXE))+++def _resolve_cli(name: str) -> list[str]:+ """Resolve the CLI entry point for subprocess tests."""+ force = os.environ.get("CLI_ANYTHING_FORCE_INSTALLED", "").strip() == "1"+ path = shutil.which(name)+ if path:+ probe = subprocess.run(+ [path, "--help"],+ capture_output=True,+ text=True,+ timeout=15,+ cwd=HARNESS_ROOT,+ )+ if probe.returncode == 0:+ return [path]+ if force:+ raise RuntimeError(+ f"{name} was found in PATH but is not runnable in this environment:\n"+ f"{probe.stderr or probe.stdout}"+ )+ if force:+ raise RuntimeError(f"{name} not found in PATH. Install with: pip install -e .")+ return [sys.executable, "-m", "cli_anything.nsight_graphics.nsight_graphics_cli"]+++CLI_BASE = _resolve_cli("cli-anything-nsight-graphics")+skip_no_nsight = pytest.mark.skipif(not HAS_NSIGHT, reason="Nsight Graphics not installed")+skip_no_target = pytest.mark.skipif(not HAS_TEST_EXE, reason="NSIGHT_GRAPHICS_TEST_EXE not set or missing")+++def _run_json(*args: str, timeout: int = 600) -> dict:+ """Run the CLI in JSON mode and parse stdout."""+ result = subprocess.run(+ CLI_BASE + ["--json", *args],+ capture_output=True,+ text=True,+ timeout=timeout,+ cwd=HARNESS_ROOT,+ )+ if result.returncode != 0:+ raise RuntimeError(f"CLI failed: {result.stderr}\n{result.stdout}")+ return json.loads(result.stdout)+++def _target_args() -> list[str]:+ """Build repeated CLI args for the configured test executable."""+ args = ["--exe", TEST_EXE]+ if TEST_WORKDIR:+ args.extend(["--dir", TEST_WORKDIR])+ if TEST_ARGS:+ for entry in shlex.split(TEST_ARGS, posix=os.name != "nt"):+ args.extend(["--arg", entry])+ return args+++@skip_no_nsight+class TestDoctorE2E:+ def test_doctor_info(self):+ data = _run_json("doctor", "info", timeout=60)+ assert data["ok"] is True+ assert data["compatibility_mode"] in {"unified", "split"}+ assert data["resolved_executable"]+++@skip_no_nsight+@skip_no_target+class TestTargetedE2E:+ def test_frame_capture(self, tmp_path):+ data = _run_json(+ "--output-dir",+ str(tmp_path),+ "frame",+ "capture",+ *_target_args(),+ "--wait-seconds",+ "1",+ )+ assert data["ok"] is True+ assert data["artifacts"]+ assert any(Path(item["path"]).exists() and item["size"] > 0 for item in data["artifacts"])++ def test_gpu_trace_capture(self, tmp_path):+ data = _run_json(+ "--output-dir",+ str(tmp_path),+ "gpu-trace",+ "capture",+ *_target_args(),+ "--start-after-ms",+ "1000",+ "--limit-to-frames",+ "1",+ "--auto-export",+ )+ assert data["ok"] is True+ assert data["artifacts"]+ assert any(Path(item["path"]).exists() and item["size"] > 0 for item in data["artifacts"])++ def test_cpp_capture(self, tmp_path):+ data = _run_json(+ "--output-dir",+ str(tmp_path),+ "cpp",+ "capture",+ *_target_args(),+ "--wait-seconds",+ "1",+ )+ assert data["ok"] is True+ assert data["artifacts"]+ assert any(Path(item["path"]).exists() and item["size"] > 0 for item in data["artifacts"])diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/__init__.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/__init__.pynew file mode 100644index 000000000..0bf4db13c--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/__init__.py@@ -0,0 +1 @@+"""Utilities for cli-anything-nsight-graphics."""diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/errors.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/errors.pynew file mode 100644index 000000000..f6877d7ea--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/errors.py@@ -0,0 +1,17 @@+"""Error handling helpers."""++from __future__ import annotations++import traceback+from typing import Any+++def handle_error(exc: Exception, debug: bool = False) -> dict[str, Any]:+ """Convert an exception into a JSON-friendly error payload."""+ payload: dict[str, Any] = {+ "error": str(exc),+ "type": type(exc).__name__,+ }+ if debug:+ payload["traceback"] = traceback.format_exc()+ return payloaddiff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/nsight_graphics_backend.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/nsight_graphics_backend.pynew file mode 100644index 000000000..637e35abd--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/nsight_graphics_backend.py@@ -0,0 +1,877 @@+"""Backend helpers for the official Nsight Graphics CLI tools."""++from __future__ import annotations++import glob+import ctypes+import os+import platform+import re+import shutil+import subprocess+from pathlib import Path+from typing import Any, Callable, Iterable, Optional, Sequence++ENV_VAR = "NSIGHT_GRAPHICS_PATH"++_BINARY_CANDIDATES = {+ "ngfx": ("ngfx.exe", "ngfx"),+ "ngfx_ui": ("ngfx-ui.exe", "ngfx-ui"),+ "ngfx_capture": ("ngfx-capture.exe", "ngfx-capture"),+ "ngfx_replay": ("ngfx-replay.exe", "ngfx-replay"),+}++INSTALL_INSTRUCTIONS = (+ "Nsight Graphics CLI tools were not found.\n"+ "Install NVIDIA Nsight Graphics and make sure ngfx.exe is available, or set "+ f"{ENV_VAR} to the install directory or executable path.\n"+ "Typical Windows location:\n"+ " C:\\Program Files\\NVIDIA Corporation\\Nsight Graphics <version>\\host\\windows-desktop-nomad-x64"+)+++def _command_string(args: Sequence[str]) -> str:+ """Render a command for display."""+ if platform.system() == "Windows":+ return subprocess.list2cmdline(list(args))+ return " ".join(args)+++def _dedupe(values: Iterable[str]) -> list[str]:+ """Deduplicate while preserving order."""+ seen: set[str] = set()+ result: list[str] = []+ for value in values:+ normalized = os.path.normcase(os.path.normpath(value))+ if normalized in seen:+ continue+ seen.add(normalized)+ result.append(value)+ return result+++def _scan_directory(directory: str) -> dict[str, str]:+ """Scan a directory for known Nsight binaries."""+ found: dict[str, str] = {}+ base = Path(directory)+ if not base.is_dir():+ return found+ for key, candidates in _BINARY_CANDIDATES.items():+ for candidate in candidates:+ path = base / candidate+ if path.is_file():+ found[key] = str(path.resolve())+ break+ return found+++def _candidate_dirs_from_env(path_value: str) -> list[str]:+ """Resolve environment override into candidate directories."""+ if not path_value:+ return []+ path = Path(path_value)+ candidates: list[str] = []+ if path.is_file():+ candidates.append(str(path.parent))+ else:+ candidates.append(str(path))+ candidates.append(str(path / "host" / "windows-desktop-nomad-x64"))+ candidates.append(str(path / "windows-desktop-nomad-x64"))+ return _dedupe([p for p in candidates if Path(p).exists()])+++def _default_windows_install_dirs(+ glob_func: Callable[[str], list[str]],+) -> list[str]:+ """Return default Windows install directories for Nsight Graphics."""+ drive_roots = _fixed_windows_drive_roots()+ if not drive_roots:+ drive_roots = ["C:"]++ patterns: list[str] = []+ for drive in drive_roots:+ patterns.extend(+ [+ f"{drive}/Program Files/NVIDIA Corporation/Nsight Graphics */host/windows-desktop-nomad-x64",+ f"{drive}/Program Files (x86)/NVIDIA Corporation/Nsight Graphics */host/windows-desktop-nomad-x64",+ ]+ )+ matches: list[str] = []+ for pattern in patterns:+ matches.extend(glob_func(pattern))+ return _dedupe(+ sorted(+ matches,+ key=lambda path: (_version_sort_key(_extract_version_from_path(path)), path),+ reverse=True,+ )+ )+++def _fixed_windows_drive_roots() -> list[str]:+ """Return fixed-drive roots such as C: and D: on Windows."""+ if platform.system() != "Windows":+ return []+ try:+ drive_mask = ctypes.windll.kernel32.GetLogicalDrives()+ get_drive_type = ctypes.windll.kernel32.GetDriveTypeW+ except Exception:+ return []++ DRIVE_FIXED = 3+ drives: list[str] = []+ for index in range(26):+ if not (drive_mask & (1 << index)):+ continue+ letter = chr(ord("A") + index)+ root = f"{letter}:\\"+ try:+ if get_drive_type(root) == DRIVE_FIXED:+ drives.append(f"{letter}:")+ except Exception:+ continue+ return drives+++def _read_registry_installations(+ platform_system: Optional[str] = None,+) -> list[dict[str, Any]]:+ """Read Nsight Graphics install records from the Windows uninstall registry."""+ platform_system = platform.system() if platform_system is None else platform_system+ if platform_system != "Windows":+ return []++ try:+ import winreg+ except ImportError:+ return []++ uninstall_roots = [+ (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"),+ (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"),+ ]++ def _query_value(key, name: str) -> Optional[str]:+ try:+ value, _ = winreg.QueryValueEx(key, name)+ except OSError:+ return None+ if value is None:+ return None+ text = str(value).strip()+ return text or None++ records: list[dict[str, Any]] = []+ for hive, root in uninstall_roots:+ try:+ with winreg.OpenKey(hive, root) as root_key:+ index = 0+ while True:+ try:+ subkey_name = winreg.EnumKey(root_key, index)+ except OSError:+ break+ index += 1+ try:+ with winreg.OpenKey(root_key, subkey_name) as subkey:+ display_name = _query_value(subkey, "DisplayName")+ if not display_name or "Nsight Graphics" not in display_name:+ continue+ records.append(+ {+ "display_name": display_name,+ "display_version": _query_value(subkey, "DisplayVersion"),+ "install_location": _query_value(subkey, "InstallLocation"),+ "install_source": _query_value(subkey, "InstallSource"),+ "uninstall_string": _query_value(subkey, "UninstallString"),+ "publisher": _query_value(subkey, "Publisher"),+ "registry_key": f"HKLM\\{root}\\{subkey_name}",+ }+ )+ except OSError:+ continue+ except OSError:+ continue+ return records+++def _override_value(+ env: dict[str, str],+ nsight_path: Optional[str] = None,+) -> str:+ """Resolve the effective override path from CLI or environment."""+ if nsight_path and nsight_path.strip():+ return nsight_path.strip()+ return env.get(ENV_VAR, "").strip()+++def discover_binaries(+ env: Optional[dict[str, str]] = None,+ which: Optional[Callable[[str], Optional[str]]] = None,+ glob_func: Optional[Callable[[str], list[str]]] = None,+ platform_system: Optional[str] = None,+ nsight_path: Optional[str] = None,+) -> dict[str, Any]:+ """Discover available Nsight binaries."""+ env = os.environ if env is None else env+ which = shutil.which if which is None else which+ glob_func = glob.glob if glob_func is None else glob_func+ platform_system = platform.system() if platform_system is None else platform_system++ binaries: dict[str, Optional[str]] = {+ "ngfx": None,+ "ngfx_ui": None,+ "ngfx_capture": None,+ "ngfx_replay": None,+ }+ search_roots: list[str] = []+ override = _override_value(env, nsight_path=nsight_path)++ if override:+ override_path = Path(override)+ if override_path.is_file():+ for key, candidates in _BINARY_CANDIDATES.items():+ lowered = {name.lower() for name in candidates}+ if override_path.name.lower() in lowered:+ binaries[key] = str(override_path.resolve())+ break+ search_roots.extend(_candidate_dirs_from_env(override))++ for key, candidates in _BINARY_CANDIDATES.items():+ for candidate in candidates:+ resolved = which(candidate)+ if resolved:+ binaries[key] = binaries[key] or str(Path(resolved).resolve())+ search_roots.append(str(Path(resolved).resolve().parent))+ break++ if platform_system == "Windows":+ search_roots.extend(_default_windows_install_dirs(glob_func))++ for directory in _dedupe(search_roots):+ found = _scan_directory(directory)+ for key, value in found.items():+ binaries[key] = binaries[key] or value++ return {+ "binaries": binaries,+ "search_roots": _dedupe(search_roots),+ "env_override": env.get(ENV_VAR, "").strip() or None,+ "cli_override": nsight_path.strip() if nsight_path and nsight_path.strip() else None,+ "effective_override": override or None,+ }+++def list_installations(+ env: Optional[dict[str, str]] = None,+ which: Optional[Callable[[str], Optional[str]]] = None,+ glob_func: Optional[Callable[[str], list[str]]] = None,+ platform_system: Optional[str] = None,+ nsight_path: Optional[str] = None,+) -> dict[str, Any]:+ """List installed Nsight Graphics directories and versions."""+ env = os.environ if env is None else env+ which = shutil.which if which is None else which+ glob_func = glob.glob if glob_func is None else glob_func+ platform_system = platform.system() if platform_system is None else platform_system++ discovered = discover_binaries(+ env=env,+ which=which,+ glob_func=glob_func,+ platform_system=platform_system,+ nsight_path=nsight_path,+ )+ selected_path = _primary_executable(discovered["binaries"])++ candidates: list[str] = []+ for root in discovered["search_roots"]:+ candidates.append(root)+ if platform_system == "Windows":+ candidates.extend(_default_windows_install_dirs(glob_func))+ if nsight_path:+ candidates.extend(_candidate_dirs_from_env(nsight_path))+ if env.get(ENV_VAR, "").strip():+ candidates.extend(_candidate_dirs_from_env(env[ENV_VAR]))+ for key, names in _BINARY_CANDIDATES.items():+ for name in names:+ resolved = which(name)+ if resolved:+ candidates.append(str(Path(resolved).resolve().parent))+ break++ installations: list[dict[str, Any]] = []+ installation_keys: set[str] = set()+ for directory in _dedupe(candidates):+ found = _scan_directory(directory)+ if not found:+ continue+ primary = _primary_executable(found)+ key = f"fs::{os.path.normcase(os.path.normpath(directory))}"+ installation_keys.add(key)+ installations.append(+ {+ "install_root": directory,+ "version": _extract_version_from_path(directory) or _extract_version_from_path(primary or ""),+ "tool_mode": detect_tool_mode(found),+ "selected": bool(primary and selected_path and os.path.normcase(primary) == os.path.normcase(selected_path)),+ "discovery_sources": ["filesystem"],+ "registered_only": False,+ "registry_key": None,+ "display_name": None,+ "display_version": None,+ "install_source": None,+ "binaries": {+ key: found.get(key) for key in ("ngfx", "ngfx_ui", "ngfx_capture", "ngfx_replay")+ },+ }+ )++ for record in _read_registry_installations(platform_system=platform_system):+ install_location = record.get("install_location")+ normalized_location = None+ if install_location:+ normalized_location = os.path.normcase(os.path.normpath(install_location))+ guessed_version = (+ _extract_version_from_text(record.get("display_name") or "")+ or _extract_version_from_text(record.get("display_version") or "")+ )++ matched_entry = None+ if normalized_location:+ for item in installations:+ item_root = item.get("install_root")+ if item_root and os.path.normcase(os.path.normpath(item_root)) == normalized_location:+ matched_entry = item+ break+ elif guessed_version:+ same_version = [+ item+ for item in installations+ if not item.get("registered_only") and item.get("version") == guessed_version+ ]+ if len(same_version) == 1:+ matched_entry = same_version[0]++ if matched_entry is not None:+ matched_entry["discovery_sources"] = _dedupe(+ list(matched_entry.get("discovery_sources", [])) + ["registry"]+ )+ matched_entry["display_name"] = record.get("display_name")+ matched_entry["display_version"] = record.get("display_version")+ matched_entry["registry_key"] = record.get("registry_key")+ matched_entry["install_source"] = record.get("install_source")+ if not matched_entry.get("version"):+ matched_entry["version"] = guessed_version+ continue++ registry_key = f"reg::{record['registry_key']}"+ if registry_key in installation_keys:+ continue+ installation_keys.add(registry_key)+ installations.append(+ {+ "install_root": install_location or None,+ "version": guessed_version,+ "tool_mode": "registered-only",+ "selected": False,+ "discovery_sources": ["registry"],+ "registered_only": True,+ "registry_key": record.get("registry_key"),+ "display_name": record.get("display_name"),+ "display_version": record.get("display_version"),+ "install_source": record.get("install_source"),+ "binaries": {+ "ngfx": None,+ "ngfx_ui": None,+ "ngfx_capture": None,+ "ngfx_replay": None,+ },+ }+ )++ installations.sort(+ key=lambda item: (+ not item["selected"],+ item.get("registered_only", False),+ item.get("version") or "",+ item.get("install_root") or item.get("display_name") or "",+ ),+ reverse=False,+ )+ return {+ "ok": bool(installations),+ "selected_executable": selected_path,+ "count": len(installations),+ "installations": installations,+ "cli_override": discovered.get("cli_override"),+ "env_override": discovered.get("env_override"),+ "registry_count": sum(1 for item in installations if "registry" in item.get("discovery_sources", [])),+ }+++def detect_tool_mode(binaries: dict[str, Optional[str]]) -> str:+ """Return compatibility mode for the discovered binaries."""+ if binaries.get("ngfx_capture") or binaries.get("ngfx_replay"):+ return "split"+ if binaries.get("ngfx"):+ return "unified"+ return "missing"+++def _extract_long_option(line: str) -> Optional[str]:+ """Extract the primary long option token from a help line."""+ match = re.search(r"(--[A-Za-z0-9-]+)", line)+ return match.group(1) if match else None+++def parse_unified_help(text: str) -> dict[str, Any]:+ """Parse `ngfx --help-all` output into structured metadata."""+ activities: list[str] = []+ platforms: list[str] = []+ general_options: list[str] = []+ activity_options: dict[str, list[str]] = {}+ current_section: Optional[str] = None+ current_activity: Optional[str] = None+ collecting: Optional[str] = None++ for raw_line in text.splitlines():+ stripped = raw_line.strip()+ if not stripped:+ continue++ if stripped == "General Options:":+ current_section = "general"+ current_activity = None+ collecting = None+ continue++ if stripped.endswith("activity options:"):+ current_section = "activity"+ current_activity = stripped[: -len(" activity options:")]+ activity_options.setdefault(current_activity, [])+ collecting = None+ continue++ if stripped.startswith("--") or stripped.startswith("-"):+ option = _extract_long_option(stripped)+ if option and current_section == "general":+ general_options.append(option)+ if option == "--activity":+ collecting = "activities"+ elif option == "--platform":+ collecting = "platforms"+ else:+ collecting = None+ elif option and current_section == "activity" and current_activity:+ activity_options.setdefault(current_activity, []).append(option)+ collecting = None+ else:+ collecting = None+ continue++ if collecting == "activities":+ lowered = stripped.lower()+ if "should be one of" not in lowered and lowered not in {"of:", "one of:"}:+ activities.append(stripped)+ continue++ if collecting == "platforms":+ lowered = stripped.lower()+ if "should be one of" not in lowered and lowered not in {"of:", "one of:"}:+ platforms.append(stripped)+ continue++ return {+ "activities": _dedupe(activities),+ "platforms": _dedupe(platforms),+ "general_options": _dedupe(general_options),+ "activity_options": {+ key: _dedupe(values) for key, values in activity_options.items()+ },+ }+++def parse_option_help(text: str) -> list[str]:+ """Extract long options from arbitrary CLI help output."""+ options: list[str] = []+ for raw_line in text.splitlines():+ option = _extract_long_option(raw_line.strip())+ if option:+ options.append(option)+ return _dedupe(options)+++def _combined_output(result: dict[str, Any]) -> str:+ """Combine stdout and stderr for parsing."""+ stdout = result.get("stdout", "") or ""+ stderr = result.get("stderr", "") or ""+ return "\n".join(part for part in (stdout, stderr) if part)+++def run_command(+ args: Sequence[str],+ *,+ cwd: Optional[str] = None,+ timeout: int = 120,+) -> dict[str, Any]:+ """Run a subprocess and normalize the result."""+ try:+ proc = subprocess.run(+ list(args),+ capture_output=True,+ text=True,+ cwd=cwd,+ timeout=timeout,+ )+ return {+ "ok": proc.returncode == 0,+ "returncode": proc.returncode,+ "stdout": proc.stdout.strip(),+ "stderr": proc.stderr.strip(),+ "command": _command_string(args),+ }+ except FileNotFoundError as exc:+ return {+ "ok": False,+ "returncode": -1,+ "stdout": "",+ "stderr": str(exc),+ "command": _command_string(args),+ }+ except subprocess.TimeoutExpired:+ return {+ "ok": False,+ "returncode": -1,+ "stdout": "",+ "stderr": f"Command timed out after {timeout}s",+ "command": _command_string(args),+ }+++def _extract_version_from_text(text: str) -> Optional[str]:+ """Extract a version string from CLI output."""+ match = re.search(r"(\d{4}\.\d+(?:\.\d+)?)", text)+ if match:+ return match.group(1)+ return None+++def _extract_version_from_path(path: str) -> Optional[str]:+ """Extract a version-like token from the installation path."""+ return _extract_version_from_text(path)+++def _version_sort_key(version: Optional[str]) -> tuple[int, ...]:+ """Convert a dotted version string into a sortable tuple."""+ if not version:+ return tuple()+ parts: list[int] = []+ for token in version.split("."):+ try:+ parts.append(int(token))+ except ValueError:+ parts.append(0)+ return tuple(parts)+++def get_version(binaries: dict[str, Optional[str]]) -> Optional[str]:+ """Best-effort version detection from CLI output or path."""+ preferred = binaries.get("ngfx") or binaries.get("ngfx_capture") or binaries.get("ngfx_replay")+ if not preferred:+ return None+ result = run_command([preferred, "--version"], timeout=10)+ text = _combined_output(result)+ return _extract_version_from_text(text) or _extract_version_from_path(preferred)+++def _primary_executable(binaries: dict[str, Optional[str]]) -> Optional[str]:+ """Choose the preferred executable path to display."""+ return binaries.get("ngfx") or binaries.get("ngfx_capture") or binaries.get("ngfx_replay")+++def probe_installation(nsight_path: Optional[str] = None) -> dict[str, Any]:+ """Return an installation and capability report."""+ discovered = discover_binaries(nsight_path=nsight_path)+ binaries = discovered["binaries"]+ mode = detect_tool_mode(binaries)+ version = get_version(binaries)++ help_metadata = {+ "activities": [],+ "platforms": [],+ "general_options": [],+ "activity_options": {},+ }+ if binaries.get("ngfx"):+ help_result = run_command([binaries["ngfx"], "--help-all"], timeout=15)+ help_metadata.update(parse_unified_help(_combined_output(help_result)))++ capture_options: list[str] = []+ if binaries.get("ngfx_capture"):+ capture_help = run_command([binaries["ngfx_capture"], "--help"], timeout=15)+ capture_options = parse_option_help(_combined_output(capture_help))++ replay_options: list[str] = []+ if binaries.get("ngfx_replay"):+ replay_help = run_command([binaries["ngfx_replay"], "--help"], timeout=15)+ replay_options = parse_option_help(_combined_output(replay_help))++ warnings: list[str] = []+ host_platform = platform.system()+ if host_platform != "Windows":+ warnings.append(+ "V1 is only verified on Windows-hosted Nsight Graphics installations."+ )+ if mode == "missing":+ warnings.append(INSTALL_INSTRUCTIONS)+ if mode == "split" and not binaries.get("ngfx"):+ warnings.append(+ "Split capture/replay tools were found without ngfx.exe; launch, attach, "+ "GPU Trace, and C++ Capture helpers may be unavailable."+ )++ return {+ "ok": _primary_executable(binaries) is not None,+ "tool_mode": mode,+ "compatibility_mode": mode,+ "resolved_executable": _primary_executable(binaries),+ "version": version,+ "host_platform": host_platform,+ "verified_host": host_platform == "Windows",+ "supported_activities": help_metadata["activities"],+ "supported_platforms": help_metadata["platforms"],+ "general_options": help_metadata["general_options"],+ "activity_options": help_metadata["activity_options"],+ "split_binaries_present": {+ "ngfx_capture": bool(binaries.get("ngfx_capture")),+ "ngfx_replay": bool(binaries.get("ngfx_replay")),+ },+ "capture_options": capture_options,+ "replay_options": replay_options,+ "binaries": binaries,+ "search_roots": discovered["search_roots"],+ "env_override": discovered["env_override"],+ "cli_override": discovered.get("cli_override"),+ "effective_override": discovered.get("effective_override"),+ "warnings": warnings,+ }+++def require_binary(binaries: dict[str, Optional[str]], key: str) -> str:+ """Require a specific executable to exist."""+ path = binaries.get(key)+ if not path:+ raise RuntimeError(INSTALL_INSTRUCTIONS)+ return path+++def require_launch_target(*, project: Optional[str], exe: Optional[str]) -> None:+ """Require at least one launch target input."""+ if not project and not exe:+ raise ValueError("Specify --exe or set --project at the root level.")+++def ensure_exactly_one(label: str, flags: dict[str, bool]) -> str:+ """Validate that exactly one flag in the set is selected."""+ selected = [name for name, enabled in flags.items() if enabled]+ if len(selected) != 1:+ choices = ", ".join(flags.keys())+ raise ValueError(f"{label}: choose exactly one of {choices}.")+ return selected[0]+++def ensure_at_most_one(label: str, flags: dict[str, bool]) -> Optional[str]:+ """Validate that zero or one flags are selected."""+ selected = [name for name, enabled in flags.items() if enabled]+ if len(selected) > 1:+ choices = ", ".join(flags.keys())+ raise ValueError(f"{label}: choose at most one of {choices}.")+ return selected[0] if selected else None+++def format_env_values(envs: Sequence[str]) -> Optional[str]:+ """Format KEY=VALUE entries for ngfx.exe."""+ cleaned = [entry.strip() for entry in envs if entry and entry.strip()]+ if not cleaned:+ return None+ joined = "; ".join(cleaned)+ if not joined.endswith(";"):+ joined += ";"+ return joined+++def format_program_args(args: Sequence[str]) -> Optional[str]:+ """Format target executable arguments."""+ cleaned = [entry for entry in args if entry]+ if not cleaned:+ return None+ return subprocess.list2cmdline(cleaned)+++def build_unified_command(+ binaries: dict[str, Optional[str]],+ *,+ activity: Optional[str] = None,+ project: Optional[str] = None,+ output_dir: Optional[str] = None,+ hostname: Optional[str] = None,+ platform_name: Optional[str] = None,+ exe: Optional[str] = None,+ working_dir: Optional[str] = None,+ args: Sequence[str] = (),+ envs: Sequence[str] = (),+ attach_pid: Optional[int] = None,+ launch_detached: bool = False,+ extra_args: Sequence[str] = (),+) -> list[str]:+ """Build a command line for the unified ngfx.exe CLI."""+ ngfx = require_binary(binaries, "ngfx")+ command: list[str] = [ngfx]+ if hostname:+ command.extend(["--hostname", hostname])+ if project:+ command.extend(["--project", project])+ if output_dir:+ command.extend(["--output-dir", output_dir])+ if activity:+ command.extend(["--activity", activity])+ if platform_name:+ command.extend(["--platform", platform_name])+ if launch_detached:+ command.append("--launch-detached")+ if attach_pid is not None:+ command.extend(["--attach-pid", str(attach_pid)])+ if exe:+ command.extend(["--exe", exe])+ if working_dir:+ command.extend(["--dir", working_dir])+ formatted_args = format_program_args(args)+ if formatted_args:+ command.extend(["--args", formatted_args])+ formatted_env = format_env_values(envs)+ if formatted_env:+ command.extend(["--env", formatted_env])+ command.extend(extra_args)+ return command+++def build_split_capture_command(+ binaries: dict[str, Optional[str]],+ *,+ exe: str,+ output_dir: Optional[str] = None,+ working_dir: Optional[str] = None,+ args: Sequence[str] = (),+ envs: Sequence[str] = (),+ wait_seconds: Optional[int] = None,+ wait_frames: Optional[int] = None,+ wait_hotkey: bool = False,+ frame_count: int = 1,+) -> list[str]:+ """Build a command line for the split ngfx-capture tool."""+ capture = require_binary(binaries, "ngfx_capture")+ command: list[str] = [capture, "--exe", exe, "--frame-count", str(frame_count)]+ if output_dir:+ command.extend(["--output-dir", output_dir])+ if working_dir:+ command.extend(["--working-dir", working_dir])+ formatted_args = format_program_args(args)+ if formatted_args:+ command.extend(["--args", formatted_args])+ formatted_env = format_env_values(envs)+ if formatted_env:+ command.extend(["--env", formatted_env])++ ensure_exactly_one(+ "frame trigger",+ {+ "wait_seconds": wait_seconds is not None,+ "wait_frames": wait_frames is not None,+ "wait_hotkey": wait_hotkey,+ },+ )+ if wait_seconds is not None:+ command.extend(["--capture-countdown-timer", str(wait_seconds * 1000)])+ elif wait_frames is not None:+ command.extend(["--capture-frame", str(wait_frames)])+ else:+ command.append("--capture-hotkey")+ return command+++def default_output_dir() -> str:+ """Best-effort default output root used by the harness."""+ return str((Path.home() / "Documents" / "NVIDIA Nsight Graphics").resolve())+++def activity_artifact_roots(activity: str, output_dir: Optional[str]) -> list[str]:+ """Return directories to scan for generated artifacts."""+ if output_dir:+ return [str(Path(output_dir).resolve())]++ base = Path(default_output_dir())+ roots = [str(base)]+ normalized = activity.lower()+ if normalized == "frame debugger":+ roots.insert(0, str(base / "GraphicsCaptures"))+ elif normalized == "gpu trace profiler":+ roots.append(str(base / "GPUTrace"))+ elif normalized == "generate c++ capture":+ roots.append(str(base / "CppCaptures"))+ return _dedupe(roots)+++def snapshot_files(roots: Sequence[str]) -> dict[str, tuple[int, int]]:+ """Snapshot file mtimes and sizes under the roots."""+ snapshot: dict[str, tuple[int, int]] = {}+ for root in roots:+ root_path = Path(root)+ if not root_path.is_dir():+ continue+ for path in root_path.rglob("*"):+ if not path.is_file():+ continue+ try:+ stat = path.stat()+ except OSError:+ continue+ snapshot[str(path.resolve())] = (stat.st_mtime_ns, stat.st_size)+ return snapshot+++def diff_snapshots(+ before: dict[str, tuple[int, int]],+ after: dict[str, tuple[int, int]],+) -> list[dict[str, Any]]:+ """Return non-empty files that were created or updated."""+ artifacts: list[dict[str, Any]] = []+ for path, (mtime_ns, size) in sorted(after.items()):+ previous = before.get(path)+ if size <= 0:+ continue+ if previous is None or previous != (mtime_ns, size):+ artifacts.append(+ {+ "path": path,+ "size": size,+ "mtime_ns": mtime_ns,+ }+ )+ return artifacts+++def run_with_artifacts(+ args: Sequence[str],+ *,+ output_roots: Sequence[str],+ cwd: Optional[str] = None,+ timeout: int = 300,+) -> dict[str, Any]:+ """Run a command and discover artifacts under the supplied roots."""+ before = snapshot_files(output_roots)+ result = run_command(args, cwd=cwd, timeout=timeout)+ after = snapshot_files(output_roots)+ result["artifacts"] = diff_snapshots(before, after)+ result["artifact_count"] = len(result["artifacts"])+ return resultdiff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/output.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/output.pynew file mode 100644index 000000000..394ccf740--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/output.py@@ -0,0 +1,15 @@+"""Output helpers."""++from __future__ import annotations++import json+import sys+from typing import Any+++def output_json(data: Any, indent: int = 2, file=None) -> None:+ """Write JSON to stdout or a supplied file object."""+ if file is None:+ file = sys.stdout+ json.dump(data, file, indent=indent, default=str)+ file.write("\n")diff --git a/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/repl_skin.py b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/repl_skin.pynew file mode 100644index 000000000..b8fc47efa--- /dev/null+++ b/nsight-graphics/agent-harness/cli_anything/nsight_graphics/utils/repl_skin.py@@ -0,0 +1,59 @@+"""Small REPL skin used by cli-anything-nsight-graphics."""++from __future__ import annotations++from pathlib import Path+++class ReplSkin:+ """Minimal REPL helper with lightweight styling."""++ def __init__(self, software: str, version: str = "0.1.0"):+ self.software = software+ self.version = version+ self.history_file = str(Path.home() / f".cli-anything-{software}" / "history")+ Path(self.history_file).parent.mkdir(parents=True, exist_ok=True)+ skill_path = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"+ self.skill_path = str(skill_path) if skill_path.is_file() else None++ def print_banner(self) -> None:+ print(f"cli-anything Β· {self.software} v{self.version}")+ if self.skill_path:+ print(f"Skill: {self.skill_path}")+ print("Type help for commands, quit to exit.\n")++ def create_prompt_session(self):+ try:+ from prompt_toolkit import PromptSession+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory+ from prompt_toolkit.history import FileHistory++ return PromptSession(+ history=FileHistory(self.history_file),+ auto_suggest=AutoSuggestFromHistory(),+ enable_history_search=True,+ )+ except ImportError:+ return None++ def get_input(self, session, project_name: str = "", modified: bool = False) -> str:+ suffix = f"[{project_name}]" if project_name else ""+ prompt = f"{self.software}{suffix}> "+ if session is None:+ return input(prompt).strip()+ return session.prompt(prompt).strip()++ def help(self, commands: dict[str, str]) -> None:+ print("Commands:")+ for name, description in commands.items():+ print(f" {name:<14} {description}")+ print()++ def warning(self, message: str) -> None:+ print(f"[warn] {message}")++ def error(self, message: str) -> None:+ print(f"[error] {message}")++ def print_goodbye(self) -> None:+ print("\nGoodbye.\n")diff --git a/nsight-graphics/agent-harness/setup.py b/nsight-graphics/agent-harness/setup.pynew file mode 100644index 000000000..bfa2e2c60--- /dev/null+++ b/nsight-graphics/agent-harness/setup.py@@ -0,0 +1,41 @@+"""Setup for cli-anything-nsight-graphics package."""++from pathlib import Path++from setuptools import find_namespace_packages, setup++_README = Path(__file__).parent / "cli_anything" / "nsight_graphics" / "README.md"+_LONG_DESC = _README.read_text(encoding="utf-8") if _README.is_file() else ""++setup(+ name="cli-anything-nsight-graphics",+ version="0.1.0",+ description="CLI harness for NVIDIA Nsight Graphics orchestration",+ long_description=_LONG_DESC,+ long_description_content_type="text/markdown",+ author="cli-anything",+ packages=find_namespace_packages(include=["cli_anything.*"]),+ python_requires=">=3.10",+ install_requires=[+ "click>=8.0",+ "prompt-toolkit>=3.0",+ ],+ extras_require={+ "test": ["pytest>=7.0"],+ },+ entry_points={+ "console_scripts": [+ "cli-anything-nsight-graphics=cli_anything.nsight_graphics.nsight_graphics_cli:main",+ ],+ },+ package_data={+ "cli_anything.nsight_graphics": ["skills/*.md", "README.md"],+ },+ include_package_data=True,+ zip_safe=False,+ classifiers=[+ "Programming Language :: Python :: 3",+ "License :: OSI Approved :: MIT License",+ "Topic :: Software Development :: Debuggers",+ ],+)diff --git a/registry.json b/registry.jsonindex b20c870f7..559e30d78 100644--- a/registry.json+++ b/registry.json@@ -397,6 +397,20 @@"contributor": "levishilf","contributor_url": "https://github.com/levishilf"},+ {+ "name": "nsight-graphics",+ "display_name": "Nsight Graphics",+ "version": "0.1.0",+ "description": "Windows-first orchestration of Nsight Graphics launch, Frame Debugger capture, GPU Trace, and Generate C++ Capture",+ "requires": "NVIDIA Nsight Graphics installation with ngfx.exe or newer split capture/replay tools",+ "homepage": "https://developer.nvidia.com/nsight-graphics",+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=nsight-graphics/agent-harness",+ "entry_point": "cli-anything-nsight-graphics",+ "skill_md": "nsight-graphics/agent-harness/cli_anything/nsight_graphics/skills/SKILL.md",+ "category": "graphics",+ "contributor": "AiMiDi",+ "contributor_url": "https://github.com/AiMiDi"+ },{"name": "videocaptioner","display_name": "VideoCaptioner",