Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion config/components/catalog.json
Original file line number Diff line number Diff line change
Expand Up @@ -28871,7 +28871,7 @@
"title": "threejs-network-viz",
"description": "Generate browser-based interactive 3D network topology visualizations from inventory or a topology description. Use when a portable HTML scene is wanted without a desktop 3D engine.",
"path": "workspace/skills/threejs-network-viz/SKILL.md",
"sha256": "9ad3994b6b0e6eebe655cb9ca1e696246b644f7a2172df5fa0554fee317613ad",
"sha256": "6f591a70ffc07415a5413eb5a9bf184cf1604a25bdaba231542f2965049e1151",
"components": [
"threejs-viz"
],
Expand Down
2 changes: 1 addition & 1 deletion scripts/lib/catalog.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Generated by scripts/build-catalog.py; edit config/components/catalog.json.
# Catalog SHA-256: dca976ecf86784d1ad75538c93ce8e78a94114c76884c5def928e37a96e4fa78
# Catalog SHA-256: 40985dc64a035f91bc20b51f65623ffedb06227e918294186d3b55c86ad7b616

CATALOG=(
"hermes-hud|Runtime|Hermes HUD bridge|Private HUD conversation bridge; isolated pinned Hermes companion (8 private tools)"
Expand Down
91 changes: 91 additions & 0 deletions tests/unit/test_threejs_render_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
"""
Unit tests for the threejs-network-viz command-line entry point (render.py).
An agent runs it through exec, so the contract is: on success stdout is the
absolute path of the written HTML file and nothing else, exit code 0; on any
failure stdout is empty, stderr has the reason, exit code non-zero.
"""

import json
import subprocess
import sys
from pathlib import Path

skill_path = Path(__file__).parent.parent.parent / "workspace" / "skills" / "threejs-network-viz"
RENDER = skill_path / "render.py"

TWO_NODE = {
"source": "cli-test",
"devices": [
{"hostname": "R1", "device_type": "router", "interfaces": [{"name": "Gi0/0"}]},
{"hostname": "R2", "device_type": "router", "interfaces": [{"name": "Gi0/0"}]},
],
"links": [
{"source_device": "R1", "source_interface": "Gi0/0",
"target_device": "R2", "target_interface": "Gi0/0"},
],
}


def run(*args, stdin=None, cwd=None):
return subprocess.run([sys.executable, str(RENDER), *args], input=stdin,
capture_output=True, text=True, cwd=cwd, timeout=120)


def written_path(result) -> Path:
assert result.returncode == 0, result.stderr
lines = result.stdout.strip().splitlines()
assert len(lines) == 1
path = Path(lines[0])
assert path.is_absolute() and path.is_file() and path.suffix == ".html"
return path


def test_describe_writes_html_and_prints_only_the_path(tmp_path):
r = run("--describe", "r1 is a router, sw1 is a switch, r1 connects to sw1",
"--output-dir", str(tmp_path), cwd=tmp_path)
path = written_path(r)
assert path.parent == tmp_path.resolve()
html = path.read_text(encoding="utf-8")
assert "r1" in html and "sw1" in html


def test_json_file_two_node_topology(tmp_path):
topo = tmp_path / "topo.json"
topo.write_text(json.dumps(TWO_NODE), encoding="utf-8")
path = written_path(run("--json", str(topo), "--output-dir", str(tmp_path)))
html = path.read_text(encoding="utf-8")
assert "R1" in html and "R2" in html and "Gi0/0" in html


def test_json_from_stdin_with_source(tmp_path):
r = run("--json", "-", "--source", "gns3", "--output-dir", str(tmp_path),
stdin=json.dumps(TWO_NODE))
assert "gns3" in written_path(r).name


def test_runs_from_any_working_directory(tmp_path):
other = tmp_path / "elsewhere"
other.mkdir()
written_path(run("--describe", "r1 connects to r2", "--output-dir", str(tmp_path), cwd=other))


def test_invalid_json_fails_cleanly(tmp_path):
r = run("--json", "-", "--output-dir", str(tmp_path), stdin="{not json")
assert r.returncode == 1 and r.stdout == ""
assert "threejs-network-viz: error:" in r.stderr
assert list(tmp_path.iterdir()) == []


def test_json_without_devices_list_fails(tmp_path):
r = run("--json", "-", "--output-dir", str(tmp_path), stdin='{"links": []}')
assert r.returncode == 1 and "devices" in r.stderr


def test_empty_description_fails(tmp_path):
r = run("--describe", " ", "--output-dir", str(tmp_path))
assert r.returncode == 1 and r.stdout == ""


def test_missing_input_is_usage_error():
r = run()
assert r.returncode == 2 and r.stdout == ""
33 changes: 33 additions & 0 deletions workspace/skills/threejs-network-viz/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,38 @@ Devices render as color-coded shapes by role (router, switch, firewall, load bal

Any of NetClaw's existing topology-of-record or lab-emulation integrations — Cisco Modeling Labs, GNS3, containerlab, EVE-NG, Nautobot, NetBox/Infrahub, IP Fabric, or Forward Networks — or a freeform plain-language description requiring no live source at all.

## How to run

Run the skill with **one `exec` call**. There is no MCP tool for it; do not look one up with `tool_search`.
`render.py` prints the absolute path of the written HTML file and nothing else. On failure it prints
`threejs-network-viz: error: <reason>` on stderr and exits non-zero; report that error and stop.

From a plain-language description (no live source needed):

```bash
python3 skills/threejs-network-viz/render.py --describe "R1 is a router, R2 is a router, R1 connects to R2"
```

From topology JSON (a file, or `-` for stdin). `--source` labels where the data came from
(`cml`, `gns3`, `containerlab`, `eve_ng`, `nautobot`, `netbox_infrahub`, `ip_fabric`, `forward_networks`; default `cml`):

```bash
python3 skills/threejs-network-viz/render.py --json topology.json --source cml
```

```json
{"source": "lab-1",
"devices": [{"hostname": "R1", "device_type": "router", "interfaces": [{"name": "Gi0/0"}]},
{"hostname": "R2", "device_type": "router", "interfaces": [{"name": "Gi0/0"}]}],
"links": [{"source_device": "R1", "source_interface": "Gi0/0",
"target_device": "R2", "target_interface": "Gi0/0"}]}
```

The paths above are relative to the workspace root (`~/.openclaw/workspace` on a standard install); from any
other directory use the full path to `render.py`. Optional flags: `--output-dir DIR` (default
`workspace/output/threejs-network-viz/`) and `--open` (also open the file in a browser; omit on headless hosts).
For a live source, fetch its topology with that source's own tools first, then pass it as JSON.

## Natural Language Commands

### Render a live topology (User Story 1 & 2)
Expand Down Expand Up @@ -82,6 +114,7 @@ Standard mouse/trackpad controls once the page is open: left-drag to rotate, scr
| `scene_builder.py` | Builds the embedded topology JSON payload consumed by the HTML template |
| `html_template.py` | Renders the single self-contained HTML file, inlining vendored Three.js r147 |
| `output.py` | Writes the timestamped output file and opens it in the browser |
| `render.py` | Command-line entry point: topology JSON or description in, written file path out (see How to run) |
| `vendor/three/` | Vendored Three.js r147 core + `OrbitControls`/`GLTFLoader` (the last release with classic global/non-module builds — see `research.md` §1-2) |

## Environment Variables
Expand Down
103 changes: 103 additions & 0 deletions workspace/skills/threejs-network-viz/render.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""
Command-line entry point for the threejs-network-viz skill.

One command turns a topology into a self-contained HTML scene and prints the
absolute path of the written file on stdout (nothing else). Errors go to
stderr with a non-zero exit code, so a calling agent can tell success from
failure without parsing prose.

Usage:
python3 render.py --describe "r1 is a router, r2 is a router, r1 connects to r2"
python3 render.py --json topology.json --source cml
cat topology.json | python3 render.py --json - --source gns3

JSON input shape (the same raw shape every live-source adapter accepts):
{"source": "label",
"devices": [{"hostname": "r1", "device_type": "router",
"interfaces": [{"name": "Gi0/0"}], "status": "healthy"}],
"links": [{"source_device": "r1", "source_interface": "Gi0/0",
"target_device": "r2", "target_interface": "Gi0/0"}]}

Exit codes: 0 written, 1 bad input or render failure, 2 usage error.
"""

import argparse
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

import output # noqa: E402
import sources # noqa: E402
from html_template import render_html # noqa: E402
from scene_builder import build_scene_payload # noqa: E402

JSON_SOURCES = {
"cml": sources.from_cml,
"gns3": sources.from_gns3,
"containerlab": sources.from_containerlab,
"eve_ng": sources.from_eve_ng,
"nautobot": sources.from_nautobot,
"netbox_infrahub": sources.from_netbox_infrahub,
"ip_fabric": sources.from_ip_fabric,
"forward_networks": sources.from_forward_networks,
}


def _parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
prog="render.py",
description="Render a network topology as a self-contained Three.js HTML file "
"and print the file path.",
)
src = p.add_mutually_exclusive_group(required=True)
src.add_argument("--describe", metavar="TEXT",
help='plain-language topology, e.g. "r1 is a router, r1 connects to sw1"')
src.add_argument("--json", metavar="FILE",
help="topology JSON file, or - to read it from stdin")
p.add_argument("--source", choices=sorted(JSON_SOURCES), default="cml",
help="which source the JSON came from; sets the scene's source label "
"(default: cml)")
p.add_argument("--output-dir", metavar="DIR",
help="write here instead of workspace/output/threejs-network-viz/")
p.add_argument("--open", action="store_true",
help="also open the file in the default browser")
return p


def _load_json(spec: str) -> dict:
text = sys.stdin.read() if spec == "-" else Path(spec).read_text(encoding="utf-8")
data = json.loads(text)
if not isinstance(data, dict) or not isinstance(data.get("devices"), list):
raise ValueError('topology JSON must be an object with a "devices" list')
return data


def main(argv: list[str] | None = None) -> int:
args = _parser().parse_args(argv)
try:
if args.describe is not None:
if not args.describe.strip():
raise ValueError("--describe text is empty")
snapshot = sources.from_freeform(args.describe)
else:
snapshot = JSON_SOURCES[args.source](_load_json(args.json))
if not snapshot.devices:
raise ValueError("the topology has no devices")
html = render_html(build_scene_payload(snapshot))
if args.output_dir:
output.OUTPUT_DIR = Path(args.output_dir).expanduser().resolve()
path = output.write_scene(html, snapshot.snapshot_id).resolve()
except Exception as exc: # report every failure the same way to the caller
print(f"threejs-network-viz: error: {exc}", file=sys.stderr)
return 1
if args.open:
output.open_in_browser(path)
print(path)
return 0


if __name__ == "__main__":
sys.exit(main())
Loading