Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

fix: align nslogger harness with cli-anything patterns

yuhao03f0668456a3
diff --git a/nslogger/agent-harness/cli_anything/nslogger/README.md b/nslogger/agent-harness/cli_anything/nslogger/README.md
index c6c7e37df..0dd97c556 100644
--- a/nslogger/agent-harness/cli_anything/nslogger/README.md
+++ b/nslogger/agent-harness/cli_anything/nslogger/README.md
@@ -42,7 +42,8 @@ cli-anything-nslogger listen --bonjour --name bazinga --output app.log
# Write machine-readable live logs as JSON Lines
cli-anything-nslogger listen --bonjour --name bazinga --output app.jsonl --output-format jsonl
-# Interactive REPL
+# Interactive command REPL
+cli-anything-nslogger
cli-anything-nslogger repl sample.rawnsloggerdata
```
@@ -65,7 +66,7 @@ cli-anything-nslogger stats sample.rawnsloggerdata --json
| `stats` | Summary statistics |
| `listen` | Receive live NSLogger connections via Bonjour or TCP/TLS |
| `generate`| Create sample `.rawnsloggerdata` for testing |
-| `repl` | Interactive Python REPL with loaded messages |
+| `repl` | Interactive command REPL with shared cli-anything skin |
## Log Levels
diff --git a/nslogger/agent-harness/cli_anything/nslogger/nslogger_cli.py b/nslogger/agent-harness/cli_anything/nslogger/nslogger_cli.py
index 468624d67..02bdaaaf3 100644
--- a/nslogger/agent-harness/cli_anything/nslogger/nslogger_cli.py
+++ b/nslogger/agent-harness/cli_anything/nslogger/nslogger_cli.py
@@ -1,6 +1,7 @@
"""cli-anything-nslogger — CLI harness for NSLogger."""
from __future__ import annotations
import json
+import shlex
import sys
import os
from datetime import datetime, timezone
@@ -13,6 +14,7 @@ from .core.filter import filter_messages
from .core.stats import compute_stats
from .core.exporter import export_messages
from .core.message import LEVEL_NAMES, MSG_TYPE_CLIENT_INFO
+from .utils.repl_skin import ReplSkin
CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
@@ -76,9 +78,10 @@ def _open_live_output_file(path: str, append: bool):
return open(path, mode, encoding="utf-8", buffering=1)
[email protected](context_settings=CONTEXT_SETTINGS)
[email protected](invoke_without_command=True, context_settings=CONTEXT_SETTINGS)
@click.version_option(package_name="cli-anything-nslogger")
-def cli():
+def cli(ctx):
"""NSLogger CLI — read, filter, export, and monitor NSLogger log files.
\b
@@ -95,6 +98,9 @@ def cli():
--output-format text|jsonl Write text lines or JSON Lines
--append Append instead of replacing FILE on startup
"""
+ ctx.ensure_object(dict)
+ if ctx.invoked_subcommand is None:
+ _run_repl(ctx)
# ---------------------------------------------------------------------------
@@ -513,38 +519,118 @@ def merge(files, output, fmt, level):
# ---------------------------------------------------------------------------
-# repl (interactive shell)
+# repl (interactive command shell)
# ---------------------------------------------------------------------------
[email protected]("file", type=click.Path(exists=True), required=False)
-def repl(file):
- """Start an interactive REPL for exploring NSLogger files."""
- try:
- import code
- import readline # noqa: F401
- except ImportError:
- pass
+_REPL_COMMANDS = {
+ "read [FILE]": "Display parsed messages",
+ "filter [FILE] [OPTIONS]": "Filter messages by level, tag, thread, text, regex, or range",
+ "tail [FILE]": "Show the last messages from a file",
+ "stats [FILE]": "Show summary statistics",
+ "clients [FILE]": "List client_info records",
+ "blocks [FILE]": "Show block start/end nesting",
+ "export [FILE] --format json": "Export messages as text, JSON, or CSV",
+ "merge FILE...": "Merge files by timestamp",
+ "generate OUTPUT": "Generate a sample raw NSLogger file",
+ "listen [OPTIONS]": "Listen for live NSLogger clients",
+ "load FILE": "Set the default file for file-based commands",
+ "current": "Show the current default file",
+ "help": "Show this help",
+ "quit / exit": "Exit the REPL",
+}
+
+_FILE_COMMANDS = {"read", "filter", "tail", "stats", "clients", "blocks", "export"}
+
+
+def _run_repl(ctx, file: Optional[str] = None):
+ """Launch the shared cli-anything REPL and dispatch commands through Click."""
+ skin = ReplSkin("nslogger", version="0.1.0")
+ skin.print_banner()
+
+ current_file = file
+ if current_file:
+ try:
+ message_count = sum(1 for _ in parse_file(current_file))
+ skin.success(f"Loaded {message_count} messages from {current_file}")
+ except Exception as exc:
+ skin.error(f"Could not load {current_file}: {exc}")
+ current_file = None
- context = {}
- if file:
- msgs = list(parse_file(file))
- context["messages"] = msgs
- context["file"] = file
- click.echo(f"Loaded {len(msgs)} messages from {file}")
- click.echo("Available: messages, filter_messages, compute_stats, export_messages")
- else:
- click.echo("NSLogger REPL — no file loaded. Use: messages = list(parse_file('x.rawnsloggerdata'))")
+ session = skin.create_prompt_session()
+
+ while True:
+ context = os.path.basename(current_file) if current_file else ""
+ try:
+ user_input = skin.get_input(session, context=context)
+ except (EOFError, KeyboardInterrupt):
+ skin.print_goodbye()
+ break
+
+ if not user_input:
+ continue
+
+ raw = user_input.strip()
+ command = raw.lower()
+
+ if command in ("quit", "exit", "q"):
+ skin.print_goodbye()
+ break
+
+ if command in ("help", "h", "?"):
+ skin.help(_REPL_COMMANDS)
+ continue
- context.update({
- "parse_file": parse_file,
- "filter_messages": filter_messages,
- "compute_stats": compute_stats,
- "export_messages": export_messages,
- })
+ try:
+ args = shlex.split(raw)
+ except ValueError as exc:
+ skin.error(f"Parse error: {exc}")
+ continue
+
+ if not args:
+ continue
+
+ if args[0] == "load":
+ if len(args) != 2:
+ skin.error("Usage: load FILE")
+ continue
+ if not os.path.exists(args[1]):
+ skin.error(f"File not found: {args[1]}")
+ continue
+ current_file = args[1]
+ try:
+ message_count = sum(1 for _ in parse_file(current_file))
+ skin.success(f"Loaded {message_count} messages from {current_file}")
+ except Exception as exc:
+ skin.error(f"Could not load {current_file}: {exc}")
+ current_file = None
+ continue
+
+ if args[0] == "current":
+ if current_file:
+ skin.status("File", current_file)
+ else:
+ skin.info("No default file loaded.")
+ continue
+
+ if args[0] in _FILE_COMMANDS and current_file and (len(args) == 1 or args[1].startswith("-")):
+ args.insert(1, current_file)
+
+ try:
+ cli.main(args=args, obj=ctx.obj, standalone_mode=False)
+ except SystemExit:
+ pass
+ except click.exceptions.ClickException as exc:
+ skin.error(exc.format_message())
+ except Exception as exc:
+ skin.error(str(exc))
- import code as _code
- _code.interact(local=context, banner="")
+
[email protected]("file", type=click.Path(exists=True), required=False)
+def repl(ctx, file):
+ """Start an interactive command REPL for NSLogger files."""
+ _run_repl(ctx, file=file)
def main():
diff --git a/nslogger/agent-harness/cli_anything/nslogger/skills/SKILL.md b/nslogger/agent-harness/cli_anything/nslogger/skills/SKILL.md
index 5ead7b0fb..664470c08 100644
--- a/nslogger/agent-harness/cli_anything/nslogger/skills/SKILL.md
+++ b/nslogger/agent-harness/cli_anything/nslogger/skills/SKILL.md
@@ -128,11 +128,11 @@ the CLI publishes a native macOS `NetService` with `_nslogger-ssl._tcp` and
accepts TLS NSLogger frames. Use direct TCP/TLS only when the app is manually
configured with the Mac host and port.
-### `repl` — Interactive Python REPL
+### `repl` — Interactive Command REPL
```bash
cli-anything-nslogger repl session.rawnsloggerdata
-# Available: messages, parse_file, filter_messages, compute_stats, export_messages
+# Or launch it by running cli-anything-nslogger with no subcommand.
```
## Log Levels
diff --git a/nslogger/agent-harness/cli_anything/nslogger/tests/test_core.py b/nslogger/agent-harness/cli_anything/nslogger/tests/test_core.py
index 45167bda3..4e93df135 100644
--- a/nslogger/agent-harness/cli_anything/nslogger/tests/test_core.py
+++ b/nslogger/agent-harness/cli_anything/nslogger/tests/test_core.py
@@ -9,7 +9,9 @@ from datetime import datetime, timezone
from unittest.mock import patch
import pytest
+from click.testing import CliRunner
+import cli_anything.nslogger.nslogger_cli as nslogger_cli
from cli_anything.nslogger.core.message import (
LogMessage, MSG_TYPE_LOG, MSG_TYPE_CLIENT_INFO, MSG_TYPE_BLOCK_START, MSG_TYPE_BLOCK_END,
LEVEL_NAMES,
@@ -884,3 +886,37 @@ class TestListenOutputFile:
f.write("two\n")
assert path.read_text(encoding="utf-8") == "one\ntwo\n"
+
+
+class TestCliDualMode:
+ def test_root_invokes_repl_when_no_subcommand(self, monkeypatch):
+ called = {}
+
+ def fake_run_repl(ctx, file=None):
+ called["ctx"] = ctx
+ called["file"] = file
+
+ monkeypatch.setattr(nslogger_cli, "_run_repl", fake_run_repl)
+
+ result = CliRunner().invoke(nslogger_cli.cli, [])
+
+ assert result.exit_code == 0
+ assert called["file"] is None
+ assert called["ctx"].invoked_subcommand is None
+
+ def test_repl_command_uses_shared_repl_dispatch(self, monkeypatch, tmp_path):
+ called = {}
+ log_file = tmp_path / "sample.rawnsloggerdata"
+ log_file.write_bytes(b"placeholder")
+
+ def fake_run_repl(ctx, file=None):
+ called["ctx"] = ctx
+ called["file"] = file
+
+ monkeypatch.setattr(nslogger_cli, "_run_repl", fake_run_repl)
+
+ result = CliRunner().invoke(nslogger_cli.cli, ["repl", str(log_file)])
+
+ assert result.exit_code == 0
+ assert called["file"] == str(log_file)
+ assert called["ctx"].info_name == "repl"
diff --git a/nslogger/agent-harness/setup.py b/nslogger/agent-harness/setup.py
index 92710cfa1..e6b33182a 100644
--- a/nslogger/agent-harness/setup.py
+++ b/nslogger/agent-harness/setup.py
@@ -11,7 +11,7 @@ setup(
python_requires=">=3.10",
packages=find_namespace_packages(include=["cli_anything.*"]),
package_data={
- "cli_anything.nslogger": ["helpers/*.swift"],
+ "cli_anything.nslogger": ["helpers/*.swift", "skills/*.md"],
},
install_requires=[
"click>=8.0",
@@ -28,4 +28,6 @@ setup(
"License :: OSI Approved :: MIT License",
"Operating System :: MacOS",
],
+ include_package_data=True,
+ zip_safe=False,
)
diff --git a/skills/cli-anything-nslogger/SKILL.md b/skills/cli-anything-nslogger/SKILL.md
index 5ead7b0fb..664470c08 100644
--- a/skills/cli-anything-nslogger/SKILL.md
+++ b/skills/cli-anything-nslogger/SKILL.md
@@ -128,11 +128,11 @@ the CLI publishes a native macOS `NetService` with `_nslogger-ssl._tcp` and
accepts TLS NSLogger frames. Use direct TCP/TLS only when the app is manually
configured with the Mac host and port.
-### `repl` — Interactive Python REPL
+### `repl` — Interactive Command REPL
```bash
cli-anything-nslogger repl session.rawnsloggerdata
-# Available: messages, parse_file, filter_messages, compute_stats, export_messages
+# Or launch it by running cli-anything-nslogger with no subcommand.
```
## Log Levels