Skip to content

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

Python

Add LLDB harness with Windows REPL fixes

aimidif004d08804cb
diff --git a/lldb/agent-harness/HARNESS.md b/lldb/agent-harness/HARNESS.md
new file mode 100644
index 000000000..ee36a697a
--- /dev/null
+++ b/lldb/agent-harness/HARNESS.md
@@ -0,0 +1,76 @@
+# HARNESS.md - LLDB CLI Harness Specification
+
+## Overview
+
+This harness wraps the **LLDB Python API** into a Click-based CLI tool:
+`cli-anything-lldb`.
+
+It provides stateful debugging workflows for agent and script usage, with:
+- direct `import lldb` integration
+- structured dict outputs for JSON mode
+- interactive REPL with persistent debug session
+
+## Architecture
+
+```
+agent-harness/
+├── HARNESS.md
+├── LLDB.md
+├── setup.py
+└── cli_anything/
+ └── lldb/
+ ├── lldb_cli.py
+ ├── core/
+ │ ├── session.py
+ │ ├── breakpoints.py
+ │ ├── inspect.py
+ │ └── threads.py
+ ├── utils/
+ │ ├── lldb_backend.py
+ │ ├── output.py
+ │ ├── errors.py
+ │ └── repl_skin.py
+ ├── skills/SKILL.md
+ └── tests/
+```
+
+## Global Options
+
+- `--json`: machine-readable output
+- `--debug`: include traceback in errors
+- `--version`: show package version
+
+## Command Groups
+
+- `target`: create/show target
+- `process`: launch/attach/continue/detach/info
+- `breakpoint`: set/list/delete/enable/disable
+- `thread`: list/select/backtrace/info
+- `frame`: select/info/locals
+- `step`: over/into/out
+- `expr`: evaluate expression
+- `memory`: read/find
+- `core`: load core dump
+- `repl`: interactive mode (default)
+
+## Patterns
+
+1. **Lazy import of LLDB**:
+ LLDB bindings are imported only when a command actually needs a session.
+2. **Session object**:
+ `LLDBSession` owns debugger/target/process lifecycle.
+3. **Dict-first API**:
+ Core methods return JSON-serializable dict/list structures.
+4. **Dual output mode**:
+ `_output()` chooses JSON or human-friendly formatting.
+5. **Boundary errors**:
+ Command layer converts exceptions into structured error payloads.
+
+## Dependency Model
+
+LLDB is a required backend dependency:
+- macOS: `xcode-select --install`
+- Ubuntu: `sudo apt install lldb python3-lldb`
+- Windows: `winget install LLVM.LLVM`
+
+The harness auto-discovers LLDB Python bindings with `lldb -P`.
diff --git a/lldb/agent-harness/LLDB.md b/lldb/agent-harness/LLDB.md
new file mode 100644
index 000000000..41c3dcc71
--- /dev/null
+++ b/lldb/agent-harness/LLDB.md
@@ -0,0 +1,42 @@
+# LLDB.md - LLDB Backend Notes for CLI-Anything
+
+## Why LLDB Python API
+
+This harness follows the CLI-Anything principle:
+
+> Direct integration with actual software backends — full professional capabilities, zero compromises.
+
+Using `import lldb` is the native backend integration route and avoids fragile
+text parsing from `lldb -b -o ...` subprocess output.
+
+## Integration Strategy
+
+1. Try `import lldb`
+2. On failure, run `lldb -P` to discover LLDB Python module directory
+3. Prepend discovered path to `sys.path`
+4. Retry import
+
+This is implemented in `utils/lldb_backend.py`.
+
+## Session Lifecycle
+
+- Initialize LLDB debugger (`SBDebugger.Initialize`, `SBDebugger.Create`)
+- Keep one process-level session object during command/repl lifetime
+- Use synchronous mode (`SetAsync(False)`) for deterministic command behavior
+- Destroy debugger cleanly on session close
+
+## Data Model
+
+All core operations return plain dictionaries:
+- process info (`pid`, `state`, `num_threads`)
+- frame info (`function`, `file`, `line`, `address`)
+- breakpoints (`id`, `locations`, `condition`)
+- expression result (`type`, `value`, `summary`, `error`)
+
+This maps directly to `--json` output mode.
+
+## Current Limitations
+
+- No advanced watchpoint support yet
+- Memory search is a naive byte scan over fetched range
+- Multi-target workflows are not implemented yet (single active target/session)
diff --git a/lldb/agent-harness/cli_anything/lldb/README.md b/lldb/agent-harness/cli_anything/lldb/README.md
new file mode 100644
index 000000000..3cdb56c22
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/README.md
@@ -0,0 +1,91 @@
+# cli-anything-lldb
+
+Command-line interface for LLDB debugger using LLDB Python API.
+
+## Installation
+
+```bash
+cd lldb/agent-harness
+pip install -e .
+```
+
+## LLDB Prerequisites
+
+Install LLDB:
+
+```bash
+# macOS
+xcode-select --install
+
+# Ubuntu
+sudo apt install lldb python3-lldb
+
+# Windows
+winget install LLVM.LLVM
+```
+
+Ensure `lldb` is on `PATH`. The harness auto-discovers Python bindings via:
+
+```bash
+lldb -P
+```
+
+## Quick Start
+
+```bash
+# Show help
+cli-anything-lldb --help
+
+# Create a target
+cli-anything-lldb --json target create --exe /path/to/executable
+
+# Launch process
+cli-anything-lldb --json process launch --arg foo --arg bar
+
+# Set breakpoint by function
+cli-anything-lldb --json breakpoint set --function main
+
+# Continue and inspect
+cli-anything-lldb --json process continue
+cli-anything-lldb --json thread backtrace
+cli-anything-lldb --json frame locals
+
+# Evaluate expression
+cli-anything-lldb --json expr "argc"
+
+# Start REPL (default mode)
+cli-anything-lldb
+```
+
+## Command Groups
+
+- `target`: `create`, `info`
+- `process`: `launch`, `attach`, `continue`, `detach`, `info`
+- `breakpoint`: `set`, `list`, `delete`, `enable`, `disable`
+- `thread`: `list`, `select`, `backtrace`, `info`
+- `frame`: `select`, `info`, `locals`
+- `step`: `over`, `into`, `out`
+- `expr`
+- `memory`: `read`, `find`
+- `core`: `load`
+- `repl`
+
+## JSON Output
+
+Use `--json` for all commands in agent workflows:
+
+```bash
+cli-anything-lldb --json process info
+```
+
+## Testing
+
+```bash
+cd lldb/agent-harness
+pytest cli_anything/lldb/tests/test_core.py -v
+pytest cli_anything/lldb/tests/test_full_e2e.py -v
+```
+
+E2E tests require:
+- `LLDB_TEST_EXE` pointing to a runnable test executable
+- optional `LLDB_TEST_CORE` for core-load scenario
diff --git a/lldb/agent-harness/cli_anything/lldb/__init__.py b/lldb/agent-harness/cli_anything/lldb/__init__.py
new file mode 100644
index 000000000..ebd6bf23f
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/__init__.py
@@ -0,0 +1,6 @@
+"""LLDB CLI harness - command-line interface for LLDB debugger."""
+
+__version__ = "0.1.0"
+
+# The ``lldb`` module is loaded lazily by backend/core code when needed.
+# Install LLDB and ensure its Python bindings are discoverable.
diff --git a/lldb/agent-harness/cli_anything/lldb/__main__.py b/lldb/agent-harness/cli_anything/lldb/__main__.py
new file mode 100644
index 000000000..357eefa25
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/__main__.py
@@ -0,0 +1,5 @@
+"""Allow running as python -m cli_anything.lldb."""
+
+from cli_anything.lldb.lldb_cli import main
+
+main()
diff --git a/lldb/agent-harness/cli_anything/lldb/core/__init__.py b/lldb/agent-harness/cli_anything/lldb/core/__init__.py
new file mode 100644
index 000000000..fc92d143e
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/core/__init__.py
@@ -0,0 +1 @@
+"""Core modules for LLDB CLI harness."""
diff --git a/lldb/agent-harness/cli_anything/lldb/core/breakpoints.py b/lldb/agent-harness/cli_anything/lldb/core/breakpoints.py
new file mode 100644
index 000000000..935938470
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/core/breakpoints.py
@@ -0,0 +1,23 @@
+"""
+Higher-level breakpoint helpers built on LLDBSession.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, Optional
+
+
+def set_breakpoint(session, file: Optional[str] = None, line: Optional[int] = None, function: Optional[str] = None, condition: Optional[str] = None) -> Dict[str, Any]:
+ return session.breakpoint_set(file=file, line=line, function=function, condition=condition)
+
+
+def list_breakpoints(session) -> Dict[str, Any]:
+ return session.breakpoint_list()
+
+
+def delete_breakpoint(session, bp_id: int) -> Dict[str, Any]:
+ return session.breakpoint_delete(bp_id)
+
+
+def set_enabled(session, bp_id: int, enabled: bool) -> Dict[str, Any]:
+ return session.breakpoint_enable(bp_id, enabled=enabled)
diff --git a/lldb/agent-harness/cli_anything/lldb/core/inspect.py b/lldb/agent-harness/cli_anything/lldb/core/inspect.py
new file mode 100644
index 000000000..c16e75ee3
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/core/inspect.py
@@ -0,0 +1,19 @@
+"""
+Inspection helpers for variables, expressions, and memory.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+
+def list_locals(session) -> Dict[str, Any]:
+ return session.locals()
+
+
+def evaluate_expression(session, expression: str) -> Dict[str, Any]:
+ return session.evaluate(expression)
+
+
+def read_memory(session, address: int, size: int) -> Dict[str, Any]:
+ return session.read_memory(address, size)
diff --git a/lldb/agent-harness/cli_anything/lldb/core/session.py b/lldb/agent-harness/cli_anything/lldb/core/session.py
new file mode 100644
index 000000000..2493c9b0a
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/core/session.py
@@ -0,0 +1,333 @@
+"""
+Stateful LLDB session wrapper built on LLDB Python API.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Any, Dict, List, Optional
+
+from cli_anything.lldb.utils.lldb_backend import ensure_lldb_importable
+
+
+class LLDBSession:
+ """Encapsulates one LLDB debugger session using Python API only."""
+
+ _STATE_NAMES = {
+ 0: "invalid",
+ 1: "unloaded",
+ 2: "connected",
+ 3: "attaching",
+ 4: "launching",
+ 5: "stopped",
+ 6: "running",
+ 7: "stepping",
+ 8: "crashed",
+ 9: "detached",
+ 10: "exited",
+ 11: "suspended",
+ }
+
+ def __init__(self):
+ self._lldb = ensure_lldb_importable()
+ self._lldb.SBDebugger.Initialize()
+ self.debugger = self._lldb.SBDebugger.Create()
+ self.debugger.SetAsync(False)
+ self.target = None
+ self.process = None
+
+ def target_create(self, exe_path: str, arch: Optional[str] = None) -> Dict[str, Any]:
+ arch = arch or self._lldb.LLDB_ARCH_DEFAULT
+ self.target = self.debugger.CreateTargetWithFileAndArch(exe_path, arch)
+ if not self.target or not self.target.IsValid():
+ raise RuntimeError(f"Failed to create target: {exe_path}")
+ return {
+ "executable": exe_path,
+ "arch": arch,
+ "triple": self.target.GetTriple(),
+ }
+
+ def target_info(self) -> Dict[str, Any]:
+ self._require_target()
+ exe = self.target.GetExecutable()
+ return {
+ "triple": self.target.GetTriple(),
+ "executable": str(exe) if exe else None,
+ "byte_order": str(self.target.GetByteOrder()),
+ "address_byte_size": self.target.GetAddressByteSize(),
+ "num_modules": self.target.GetNumModules(),
+ "num_breakpoints": self.target.GetNumBreakpoints(),
+ }
+
+ def attach_pid(self, pid: int) -> Dict[str, Any]:
+ self._require_target()
+ error = self._lldb.SBError()
+ listener = self.debugger.GetListener()
+ self.process = self.target.AttachToProcessWithID(listener, pid, error)
+ if not error.Success():
+ raise RuntimeError(f"Attach failed: {error}")
+ return self._process_info()
+
+ def attach_name(self, name: str, wait_for: bool = False) -> Dict[str, Any]:
+ self._require_target()
+ attach_info = self._lldb.SBAttachInfo()
+ attach_info.SetExecutable(name)
+ if wait_for:
+ attach_info.SetWaitForLaunch(True, False)
+ error = self._lldb.SBError()
+ self.process = self.target.Attach(attach_info, error)
+ if not error.Success():
+ raise RuntimeError(f"Attach failed: {error}")
+ return self._process_info()
+
+ def launch(
+ self,
+ args: Optional[List[str]] = None,
+ env: Optional[List[str]] = None,
+ working_dir: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ self._require_target()
+ self.process = self.target.LaunchSimple(args, env, working_dir or os.getcwd())
+ if not self.process or not self.process.IsValid():
+ raise RuntimeError("Launch failed")
+ return self._process_info()
+
+ def detach(self) -> Dict[str, Any]:
+ self._require_process()
+ error = self.process.Detach()
+ if not error.Success():
+ raise RuntimeError(f"Detach failed: {error}")
+ return {"status": "detached"}
+
+ def breakpoint_set(
+ self,
+ file: Optional[str] = None,
+ line: Optional[int] = None,
+ function: Optional[str] = None,
+ condition: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ self._require_target()
+ if function:
+ bp = self.target.BreakpointCreateByName(function)
+ elif file and line:
+ bp = self.target.BreakpointCreateByLocation(file, line)
+ else:
+ raise ValueError("Specify --file/--line or --function")
+ if not bp or not bp.IsValid():
+ raise RuntimeError("Failed to create breakpoint")
+ if condition:
+ bp.SetCondition(condition)
+ return {
+ "id": bp.GetID(),
+ "locations": bp.GetNumLocations(),
+ "condition": condition,
+ }
+
+ def breakpoint_list(self) -> Dict[str, Any]:
+ self._require_target()
+ bps = []
+ for i in range(self.target.GetNumBreakpoints()):
+ bp = self.target.GetBreakpointAtIndex(i)
+ bps.append(
+ {
+ "id": bp.GetID(),
+ "hits": bp.GetHitCount(),
+ "locations": bp.GetNumLocations(),
+ "enabled": bp.IsEnabled(),
+ "condition": bp.GetCondition() or None,
+ }
+ )
+ return {"breakpoints": bps}
+
+ def breakpoint_delete(self, bp_id: int) -> Dict[str, Any]:
+ self._require_target()
+ deleted = self.target.BreakpointDelete(bp_id)
+ if not deleted:
+ raise RuntimeError(f"Failed to delete breakpoint: {bp_id}")
+ return {"deleted": bp_id}
+
+ def breakpoint_enable(self, bp_id: int, enabled: bool = True) -> Dict[str, Any]:
+ self._require_target()
+ bp = self.target.FindBreakpointByID(bp_id)
+ if not bp or not bp.IsValid():
+ raise RuntimeError(f"Breakpoint not found: {bp_id}")
+ bp.SetEnabled(enabled)
+ return {"id": bp_id, "enabled": bool(enabled)}
+
+ def step_over(self) -> Dict[str, Any]:
+ self._current_thread().StepOver()
+ return self._frame_info()
+
+ def step_into(self) -> Dict[str, Any]:
+ self._current_thread().StepInto()
+ return self._frame_info()
+
+ def step_out(self) -> Dict[str, Any]:
+ self._current_thread().StepOut()
+ return self._frame_info()
+
+ def continue_exec(self) -> Dict[str, Any]:
+ self._require_process()
+ self.process.Continue()
+ return self._process_info()
+
+ def backtrace(self, limit: int = 50) -> Dict[str, Any]:
+ thread = self._current_thread()
+ frames = []
+ for i in range(min(thread.GetNumFrames(), limit)):
+ f = thread.GetFrameAtIndex(i)
+ line_entry = f.GetLineEntry()
+ frames.append(
+ {
+ "index": i,
+ "function": f.GetFunctionName(),
+ "file": str(line_entry.GetFileSpec()) if line_entry.IsValid() else None,
+ "line": line_entry.GetLine() if line_entry.IsValid() else None,
+ "address": hex(f.GetPC()),
+ }
+ )
+ return {"thread_id": thread.GetThreadID(), "frames": frames}
+
+ def locals(self) -> Dict[str, Any]:
+ frame = self._current_frame()
+ variables = frame.GetVariables(True, True, False, True)
+ result = []
+ for v in variables:
+ result.append(
+ {
+ "name": v.GetName(),
+ "type": v.GetTypeName(),
+ "value": v.GetValue(),
+ "summary": v.GetSummary(),
+ }
+ )
+ return {"variables": result}
+
+ def evaluate(self, expr: str) -> Dict[str, Any]:
+ frame = self._current_frame()
+ val = frame.EvaluateExpression(expr)
+ return {
+ "expression": expr,
+ "type": val.GetTypeName(),
+ "value": val.GetValue(),
+ "summary": val.GetSummary(),
+ "error": str(val.GetError()) if not val.GetError().Success() else None,
+ }
+
+ def threads(self) -> Dict[str, Any]:
+ self._require_process()
+ result = []
+ for i in range(self.process.GetNumThreads()):
+ t = self.process.GetThreadAtIndex(i)
+ desc = self._lldb.SBStream()
+ t.GetStatus(desc)
+ result.append(
+ {
+ "index": i,
+ "id": t.GetThreadID(),
+ "name": t.GetName(),
+ "stop_reason": desc.GetData().strip(),
+ "num_frames": t.GetNumFrames(),
+ "selected": t.GetThreadID() == self.process.GetSelectedThread().GetThreadID(),
+ }
+ )
+ return {"threads": result}
+
+ def thread_select(self, thread_id: int) -> Dict[str, Any]:
+ self._require_process()
+ thread = self.process.GetThreadByID(thread_id)
+ if not thread or not thread.IsValid():
+ raise RuntimeError(f"Thread not found: {thread_id}")
+ self.process.SetSelectedThread(thread)
+ return {"selected_thread_id": thread_id}
+
+ def frame_select(self, index: int) -> Dict[str, Any]:
+ thread = self._current_thread()
+ if index < 0 or index >= thread.GetNumFrames():
+ raise RuntimeError(f"Frame index out of range: {index}")
+ frame = thread.GetFrameAtIndex(index)
+ thread.SetSelectedFrame(index)
+ line_entry = frame.GetLineEntry()
+ return {
+ "selected_frame_index": index,
+ "function": frame.GetFunctionName(),
+ "file": str(line_entry.GetFileSpec()) if line_entry.IsValid() else None,
+ "line": line_entry.GetLine() if line_entry.IsValid() else None,
+ }
+
+ def frame_info(self) -> Dict[str, Any]:
+ return self._frame_info()
+
+ def read_memory(self, address: int, size: int) -> Dict[str, Any]:
+ self._require_process()
+ error = self._lldb.SBError()
+ data = self.process.ReadMemory(address, size, error)
+ if not error.Success():
+ raise RuntimeError(f"Read memory failed: {error}")
+ return {
+ "address": hex(address),
+ "size": size,
+ "hex": data.hex(),
+ }
+
+ def load_core(self, core_path: str) -> Dict[str, Any]:
+ self._require_target()
+ self.process = self.target.LoadCore(core_path)
+ if not self.process or not self.process.IsValid():
+ raise RuntimeError(f"Failed to load core: {core_path}")
+ return self._process_info()
+
+ def destroy(self):
+ if self.process and self.process.IsValid():
+ self.process.Kill()
+ self._lldb.SBDebugger.Destroy(self.debugger)
+ self._lldb.SBDebugger.Terminate()
+
+ def _require_target(self):
+ if self.target is None or not self.target.IsValid():
+ raise RuntimeError("No target. Create target first.")
+
+ def _require_process(self):
+ if self.process is None or not self.process.IsValid():
+ raise RuntimeError("No process. Launch/attach or load core first.")
+
+ def _current_thread(self):
+ self._require_process()
+ thread = self.process.GetSelectedThread()
+ if not thread or not thread.IsValid():
+ if self.process.GetNumThreads() > 0:
+ thread = self.process.GetThreadAtIndex(0)
+ self.process.SetSelectedThread(thread)
+ else:
+ raise RuntimeError("No thread available.")
+ return thread
+
+ def _current_frame(self):
+ thread = self._current_thread()
+ frame = thread.GetSelectedFrame()
+ if not frame or not frame.IsValid():
+ if thread.GetNumFrames() > 0:
+ frame = thread.GetFrameAtIndex(0)
+ thread.SetSelectedFrame(0)
+ else:
+ raise RuntimeError("No frame available.")
+ return frame
+
+ def _process_info(self) -> Dict[str, Any]:
+ self._require_process()
+ state = self.process.GetState()
+ return {
+ "pid": self.process.GetProcessID(),
+ "state": self._STATE_NAMES.get(state, str(state)),
+ "num_threads": self.process.GetNumThreads(),
+ }
+
+ def _frame_info(self) -> Dict[str, Any]:
+ f = self._current_frame()
+ line_entry = f.GetLineEntry()
+ return {
+ "function": f.GetFunctionName(),
+ "file": str(line_entry.GetFileSpec()) if line_entry.IsValid() else None,
+ "line": line_entry.GetLine() if line_entry.IsValid() else None,
+ "address": hex(f.GetPC()),
+ }
diff --git a/lldb/agent-harness/cli_anything/lldb/core/threads.py b/lldb/agent-harness/cli_anything/lldb/core/threads.py
new file mode 100644
index 000000000..b3132bc86
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/core/threads.py
@@ -0,0 +1,19 @@
+"""
+Thread helpers for listing, selecting, and backtrace operations.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+
+def list_threads(session) -> Dict[str, Any]:
+ return session.threads()
+
+
+def select_thread(session, thread_id: int) -> Dict[str, Any]:
+ return session.thread_select(thread_id)
+
+
+def backtrace(session, limit: int = 50) -> Dict[str, Any]:
+ return session.backtrace(limit=limit)
diff --git a/lldb/agent-harness/cli_anything/lldb/lldb_cli.py b/lldb/agent-harness/cli_anything/lldb/lldb_cli.py
new file mode 100644
index 000000000..3eac7ee57
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/lldb_cli.py
@@ -0,0 +1,602 @@
+#!/usr/bin/env python3
+"""
+LLDB CLI - Command-line interface for LLDB debugger via Python API.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shlex
+from typing import Optional
+
+import click
+
+_session = None # type: ignore
+_repl_mode = False
+
+
+def _close_session():
+ global _session
+ if _session is not None:
+ _session.destroy()
+ _session = None
+
+
+def _parse_int(value: str) -> int:
+ return int(value, 0)
+
+
+def _get_session():
+ global _session
+ if _session is None:
+ from cli_anything.lldb.core.session import LLDBSession
+
+ _session = LLDBSession()
+ return _session
+
+
+def _require_target():
+ s = _get_session()
+ if s.target is None:
+ raise click.ClickException("No target. Run: target create --exe <path>")
+ return s
+
+
+def _require_process():
+ s = _require_target()
+ if s.process is None:
+ raise click.ClickException("No process. Run: process launch/attach or core load")
+ return s
+
+
+def _output(ctx: click.Context, data, human_fn=None):
+ if ctx.obj.get("json_mode"):
+ from cli_anything.lldb.utils.output import output_json
+
+ output_json(data)
+ elif human_fn:
+ human_fn(data)
+ else:
+ from cli_anything.lldb.utils.output import output_json
+
+ output_json(data)
+
+
+def _handle_exc(ctx: click.Context, exc: Exception):
+ from cli_anything.lldb.utils.errors import handle_error
+
+ err = handle_error(exc, debug=ctx.obj.get("debug", False))
+ if ctx.obj.get("json_mode"):
+ from cli_anything.lldb.utils.output import output_json
+
+ output_json(err)
+ ctx.exit(1)
+ raise click.ClickException(err["error"])
+
+
+# ===========================================================================
+# Root group
+# ===========================================================================
+
+
[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]_option(package_name="cli-anything-lldb")
+def cli(ctx, json_mode, debug):
+ """LLDB CLI - stateful debugger harness with REPL and subcommands."""
+ ctx.ensure_object(dict)
+ ctx.obj["json_mode"] = json_mode
+ ctx.obj["debug"] = debug
+ if ctx.invoked_subcommand is None:
+ ctx.invoke(repl)
+
+
+def _cleanup(ctx, _result, **_kwargs):
+ if not _repl_mode:
+ _close_session()
+
+
+# ===========================================================================
+# target
+# ===========================================================================
+
+
+def target_group():
+ """Target management."""
+
+
+@target_group.command("create")
[email protected]("--exe", "exe_path", required=True, type=click.Path(exists=False))
[email protected]("--arch", type=str, default=None, help="Target architecture (optional).")
+def target_create(ctx, exe_path: str, arch: Optional[str]):
+ """Create debug target."""
+ try:
+ data = _get_session().target_create(exe_path, arch=arch)
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@target_group.command("info")
+def target_info(ctx):
+ """Show target info."""
+ try:
+ data = _require_target().target_info()
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+# ===========================================================================
+# process
+# ===========================================================================
+
+
+def process_group():
+ """Process management."""
+
+
+@process_group.command("launch")
[email protected]("--arg", "args", multiple=True, help="Launch argument. Repeat for multiple.")
[email protected]("--env", "envs", multiple=True, help="Environment entry KEY=VALUE.")
[email protected]("--cwd", "working_dir", type=click.Path(exists=True), default=None)
+def process_launch(ctx, args, envs, working_dir):
+ """Launch process for current target."""
+ try:
+ data = _require_target().launch(
+ args=list(args) or None,
+ env=list(envs) or None,
+ working_dir=working_dir,
+ )
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@process_group.command("attach")
[email protected]("--pid", type=int, default=None, help="Attach by process ID.")
[email protected]("--name", type=str, default=None, help="Attach by process name.")
[email protected]("--wait-for", is_flag=True, help="Wait for process launch when attaching by name.")
+def process_attach(ctx, pid, name, wait_for):
+ """Attach to existing process."""
+ try:
+ s = _require_target()
+ if pid is not None:
+ data = s.attach_pid(pid)
+ elif name:
+ data = s.attach_name(name, wait_for=wait_for)
+ else:
+ raise click.ClickException("Specify --pid or --name")
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@process_group.command("continue")
+def process_continue(ctx):
+ """Continue execution."""
+ try:
+ data = _require_process().continue_exec()
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@process_group.command("detach")
+def process_detach(ctx):
+ """Detach from process."""
+ try:
+ data = _require_process().detach()
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@process_group.command("info")
+def process_info(ctx):
+ """Show process status."""
+ try:
+ data = _require_process()._process_info()
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+# ===========================================================================
+# breakpoint
+# ===========================================================================
+
+
[email protected]("breakpoint")
+def breakpoint_group():
+ """Breakpoint operations."""
+
+
+@breakpoint_group.command("set")
[email protected]("--file", "file_path", type=str, default=None)
[email protected]("--line", type=int, default=None)
[email protected]("--function", type=str, default=None)
[email protected]("--condition", type=str, default=None)
+def breakpoint_set(ctx, file_path, line, function, condition):
+ """Set a breakpoint by file/line or function."""
+ try:
+ data = _require_target().breakpoint_set(
+ file=file_path,
+ line=line,
+ function=function,
+ condition=condition,
+ )
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@breakpoint_group.command("list")
+def breakpoint_list(ctx):
+ """List breakpoints."""
+ try:
+ data = _require_target().breakpoint_list()
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@breakpoint_group.command("delete")
[email protected]("--id", "bp_id", required=True, type=int)
+def breakpoint_delete(ctx, bp_id: int):
+ """Delete breakpoint by ID."""
+ try:
+ data = _require_target().breakpoint_delete(bp_id)
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@breakpoint_group.command("enable")
[email protected]("--id", "bp_id", required=True, type=int)
+def breakpoint_enable(ctx, bp_id: int):
+ """Enable breakpoint."""
+ try:
+ data = _require_target().breakpoint_enable(bp_id, enabled=True)
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@breakpoint_group.command("disable")
[email protected]("--id", "bp_id", required=True, type=int)
+def breakpoint_disable(ctx, bp_id: int):
+ """Disable breakpoint."""
+ try:
+ data = _require_target().breakpoint_enable(bp_id, enabled=False)
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+# ===========================================================================
+# thread
+# ===========================================================================
+
+
+def thread_group():
+ """Thread operations."""
+
+
+@thread_group.command("list")
+def thread_list(ctx):
+ """List threads."""
+ try:
+ data = _require_process().threads()
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@thread_group.command("select")
[email protected]("--id", "thread_id", required=True, type=int)
+def thread_select(ctx, thread_id: int):
+ """Select thread."""
+ try:
+ data = _require_process().thread_select(thread_id)
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@thread_group.command("backtrace")
[email protected]("--limit", type=int, default=50, show_default=True)
+def thread_backtrace(ctx, limit: int):
+ """Show backtrace of selected thread."""
+ try:
+ data = _require_process().backtrace(limit=limit)
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@thread_group.command("info")
+def thread_info(ctx):
+ """Show selected thread info."""
+ try:
+ threads = _require_process().threads().get("threads", [])
+ selected = next((t for t in threads if t.get("selected")), None)
+ _output(ctx, selected or {"error": "No selected thread"})
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+# ===========================================================================
+# frame
+# ===========================================================================
+
+
+def frame_group():
+ """Frame operations."""
+
+
+@frame_group.command("select")
[email protected]("--index", required=True, type=int)
+def frame_select(ctx, index: int):
+ """Select frame by index in selected thread."""
+ try:
+ data = _require_process().frame_select(index)
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@frame_group.command("info")
+def frame_info(ctx):
+ """Show selected frame info."""
+ try:
+ data = _require_process().frame_info()
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@frame_group.command("locals")
+def frame_locals(ctx):
+ """List local variables in selected frame."""
+ try:
+ data = _require_process().locals()
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+# ===========================================================================
+# step
+# ===========================================================================
+
+
+def step_group():
+ """Single-step execution commands."""
+
+
+@step_group.command("over")
+def step_over(ctx):
+ """Step over."""
+ try:
+ data = _require_process().step_over()
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@step_group.command("into")
+def step_into(ctx):
+ """Step into."""
+ try:
+ data = _require_process().step_into()
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@step_group.command("out")
+def step_out(ctx):
+ """Step out."""
+ try:
+ data = _require_process().step_out()
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+# ===========================================================================
+# expr
+# ===========================================================================
+
+
[email protected]("expression", nargs=-1, required=True)
+def expr_eval(ctx, expression):
+ """Evaluate expression in selected frame."""
+ try:
+ expr = " ".join(expression)
+ data = _require_process().evaluate(expr)
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+# ===========================================================================
+# memory
+# ===========================================================================
+
+
+def memory_group():
+ """Memory inspection."""
+
+
+@memory_group.command("read")
[email protected]("--address", required=True, type=str, help="Address, supports hex (e.g. 0x1000).")
[email protected]("--size", required=True, type=int, help="Number of bytes to read.")
+def memory_read(ctx, address: str, size: int):
+ """Read process memory."""
+ try:
+ addr_val = _parse_int(address)
+ data = _require_process().read_memory(addr_val, size)
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@memory_group.command("find")
[email protected]("needle", required=True, type=str)
[email protected]("--start", "start_addr", required=True, type=str, help="Start address (hex/int).")
[email protected]("--size", required=True, type=int, help="Scan size in bytes.")
+def memory_find(ctx, needle: str, start_addr: str, size: int):
+ """Find ASCII needle in memory region (naive scan)."""
+ try:
+ addr_val = _parse_int(start_addr)
+ chunk = _require_process().read_memory(addr_val, size)
+ raw = bytes.fromhex(chunk["hex"])
+ idx = raw.find(needle.encode("utf-8"))
+ data = {
+ "needle": needle,
+ "start": hex(addr_val),
+ "size": size,
+ "found": idx >= 0,
+ "address": hex(addr_val + idx) if idx >= 0 else None,
+ }
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+# ===========================================================================
+# core
+# ===========================================================================
+
+
+def core_group():
+ """Core dump operations."""
+
+
+@core_group.command("load")
[email protected]("--path", "core_path", required=True, type=click.Path(exists=True))
+def core_load(ctx, core_path: str):
+ """Load a core dump into current target."""
+ try:
+ data = _require_target().load_core(core_path)
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+# ===========================================================================
+# repl
+# ===========================================================================
+
+
+def repl(ctx):
+ """Start interactive REPL session."""
+ from cli_anything.lldb.utils.repl_skin import ReplSkin
+
+ global _repl_mode
+ _repl_mode = True
+
+ skin = ReplSkin("lldb", version="0.1.0")
+ skin.print_banner()
+ pt_session = skin.create_prompt_session()
+
+ repl_commands = {
+ "target": "create|info",
+ "process": "launch|attach|continue|detach|info",
+ "breakpoint": "set|list|delete|enable|disable",
+ "thread": "list|select|backtrace|info",
+ "frame": "select|info|locals",
+ "step": "over|into|out",
+ "expr": "<expression>",
+ "memory": "read|find",
+ "core": "load",
+ "help": "Show this help",
+ "quit": "Exit REPL",
+ }
+
+ try:
+ while True:
+ try:
+ context = "attached" if _session is not None else ""
+ line = skin.get_input(pt_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(repl_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
+ _close_session()
+
+
+def main():
+ cli(obj={})
+
+
+if __name__ == "__main__":
+ main()
diff --git a/lldb/agent-harness/cli_anything/lldb/skills/SKILL.md b/lldb/agent-harness/cli_anything/lldb/skills/SKILL.md
new file mode 100644
index 000000000..9a0a95d82
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/skills/SKILL.md
@@ -0,0 +1,102 @@
+---
+name: cli-anything-lldb
+description: Stateful LLDB debugging via LLDB Python API
+version: 0.1.0
+command: cli-anything-lldb
+install: pip install cli-anything-lldb
+requires:
+ - lldb (Python bindings)
+ - click>=8.0
+ - prompt-toolkit>=3.0
+categories:
+ - debugging
+ - native
+ - lldb
+---
+
+# LLDB CLI Skill
+
+Use this CLI to run structured LLDB debugging workflows with JSON output.
+
+## Capabilities
+
+- Create debug target from executable path
+- Launch process or attach by pid/name
+- Manage breakpoints (set/list/delete/enable/disable)
+- Inspect threads, frames, locals, and backtrace
+- Evaluate expressions in current frame
+- Read/find process memory
+- Load core dumps
+- Interactive REPL with persistent session state
+
+## Quick Commands
+
+```bash
+cli-anything-lldb --json target create --exe /path/to/exe
+cli-anything-lldb --json process launch --arg foo --arg bar
+cli-anything-lldb --json breakpoint set --function main
+cli-anything-lldb --json process continue
+cli-anything-lldb --json thread backtrace --limit 20
+cli-anything-lldb --json frame locals
+cli-anything-lldb --json expr "myVar"
+cli-anything-lldb --json memory read --address 0x1000 --size 64
+```
+
+## Command Groups
+
+### target
+```bash
+cli-anything-lldb --json target create --exe /path/to/exe [--arch x86_64]
+cli-anything-lldb --json target info
+```
+
+### process
+```bash
+cli-anything-lldb --json process launch [--arg ARG ...] [--env KEY=VALUE ...] [--cwd DIR]
+cli-anything-lldb --json process attach --pid 1234
+cli-anything-lldb --json process attach --name myapp --wait-for
+cli-anything-lldb --json process continue
+cli-anything-lldb --json process detach
+cli-anything-lldb --json process info
+```
+
+### breakpoint
+```bash
+cli-anything-lldb --json breakpoint set --function main
+cli-anything-lldb --json breakpoint set --file main.c --line 42 --condition "i > 10"
+cli-anything-lldb --json breakpoint list
+cli-anything-lldb --json breakpoint delete --id 1
+cli-anything-lldb --json breakpoint enable --id 1
+cli-anything-lldb --json breakpoint disable --id 1
+```
+
+### thread / frame / step
+```bash
+cli-anything-lldb --json thread list
+cli-anything-lldb --json thread select --id 11111
+cli-anything-lldb --json thread backtrace --limit 50
+cli-anything-lldb --json frame select --index 0
+cli-anything-lldb --json frame info
+cli-anything-lldb --json frame locals
+cli-anything-lldb --json step over
+cli-anything-lldb --json step into
+cli-anything-lldb --json step out
+```
+
+### expr / memory / core
+```bash
+cli-anything-lldb --json expr "argc"
+cli-anything-lldb --json memory read --address 0x1000 --size 128
+cli-anything-lldb --json memory find "needle" --start 0x1000 --size 4096
+cli-anything-lldb --json core load --path /path/to/core
+```
+
+## Agent Usage Notes
+
+- Prefer `--json` for all automated flows.
+- Commands are stateless between separate process invocations.
+- Use REPL for persistent state:
+ - run `cli-anything-lldb`
+ - execute multi-step commands in one session
+- Call `target create` before process or core commands.
+- Expect structured errors: `{"error": "...", "type": "..."}`
diff --git a/lldb/agent-harness/cli_anything/lldb/tests/TEST.md b/lldb/agent-harness/cli_anything/lldb/tests/TEST.md
new file mode 100644
index 000000000..7affdce51
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/tests/TEST.md
@@ -0,0 +1,103 @@
+# TEST.md - LLDB CLI Test Plan
+
+## Test Inventory Plan
+
+- `test_core.py`: 24 unit tests planned
+- `test_full_e2e.py`: 9 E2E tests planned
+
+## Unit Test Plan
+
+### `utils/lldb_backend.py`
+- Validate import fallback behavior using mocked `subprocess.run`
+- Validate error path when `lldb` binary is not found
+- Validate invalid `lldb -P` output handling
+- Planned tests: 4
+
+### `utils/output.py`
+- Validate JSON emission and newline termination
+- Validate simple table rendering and empty table behavior
+- Planned tests: 3
+
+### `utils/errors.py`
+- Validate structured error dict
+- Validate debug traceback inclusion
+- Planned tests: 2
+
+### `core/session.py`
+- Validate target/process guards and high-level wrappers with mocked LLDB objects
+- Validate breakpoint set/list/delete/enable operations
+- Validate step/continue/backtrace/locals/evaluate return schemas
+- Validate thread/frame select logic
+- Planned tests: 9
+
+### `lldb_cli.py`
+- Validate `--help` for root and command groups
+- Validate JSON error behavior when no target/process exists
+- Validate subprocess invocation entrypoint
+- Planned tests: 6
+
+## E2E Test Plan
+
+### Prerequisites
+- LLDB installed and available in PATH
+- A debuggable executable path via `LLDB_TEST_EXE`
+
+### Workflows to validate
+- Create target -> launch process -> inspect process state
+- Set breakpoint -> continue -> inspect frame/locals/backtrace
+- Evaluate expression and read memory
+- Load core dump (optional; controlled by `LLDB_TEST_CORE`)
+
+### Output validation
+- All command responses parse as valid JSON in `--json` mode
+- Required keys exist (`pid`, `state`, `breakpoints`, `threads`, `frames`, etc.)
+- Commands fail with structured error payloads when prerequisites are missing
+
+## Realistic Workflow Scenarios
+
+### Workflow name: `hello_debug_session`
+- Simulates: attaching CLI agent to a simple debug loop executable
+- Operations chained:
+ 1. `target create`
+ 2. `process launch`
+ 3. `breakpoint set`
+ 4. `process continue`
+ 5. `thread backtrace`
+ 6. `frame locals`
+ 7. `expr`
+- Verified:
+ - execution state changes
+ - backtrace frame list shape
+ - expression result object shape
+
+### Workflow name: `inspect_memory_window`
+- Simulates: low-level memory inspection around known buffer addresses
+- Operations chained:
+ 1. `target create`
+ 2. `process launch`
+ 3. `memory read`
+ 4. `memory find`
+- Verified:
+ - deterministic hex payload length
+ - successful needle lookup format
+
+## Test Results
+
+### Commands run
+
+```bash
+python -m pytest cli_anything/lldb/tests/test_core.py -v
+LLDB_TEST_EXE=C:\Users\aimidi\AppData\Local\Programs\Python\Python311\python.exe python -m pytest cli_anything/lldb/tests/test_full_e2e.py -v -s
+```
+
+### Result summary
+
+- `test_core.py`: 15 passed
+- `test_full_e2e.py`: 3 passed, 1 skipped
+- Skip reason: `LLDB_TEST_CORE` was not provided, so the optional core-dump scenario was not exercised
+
+### Notes
+
+- Verified the installed `cli-anything-lldb` entrypoint on Windows after editable install
+- Fixed REPL fallback behavior for non-interactive subprocess execution on Windows
+- Fixed Windows REPL command parsing so quoted paths and inherited `--json` mode work correctly
diff --git a/lldb/agent-harness/cli_anything/lldb/tests/test_core.py b/lldb/agent-harness/cli_anything/lldb/tests/test_core.py
new file mode 100644
index 000000000..a9af01e59
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/tests/test_core.py
@@ -0,0 +1,196 @@
+"""
+Unit tests for LLDB CLI harness modules.
+
+These tests are mock-based and do not require LLDB installation.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+from click.testing import CliRunner
+
+
+def _resolve_cli(name: str):
+ """Resolve installed CLI command; fallback to module invocation for dev."""
+ import shutil
+
+ force = os.environ.get("CLI_ANYTHING_FORCE_INSTALLED", "").strip() == "1"
+ path = shutil.which(name)
+ if path:
+ return [path]
+ if force:
+ raise RuntimeError(f"{name} not found in PATH. Install with: pip install -e .")
+ return [sys.executable, "-m", "cli_anything.lldb.lldb_cli"]
+
+
+class TestOutputUtils:
+ def test_output_json(self):
+ from cli_anything.lldb.utils.output import output_json
+ import io
+
+ buf = io.StringIO()
+ output_json({"ok": True, "value": 42}, file=buf)
+ data = json.loads(buf.getvalue())
+ assert data["ok"] is True
+ assert data["value"] == 42
+
+ def test_output_table(self):
+ from cli_anything.lldb.utils.output import output_table
+ import io
+
+ buf = io.StringIO()
+ output_table([["main", 1], ["worker", 2]], ["thread", "id"], file=buf)
+ text = buf.getvalue()
+ assert "main" in text
+ assert "worker" in text
+
+ def test_output_table_empty(self):
+ from cli_anything.lldb.utils.output import output_table
+ import io
+
+ buf = io.StringIO()
+ output_table([], ["col"], file=buf)
+ assert "(no data)" in buf.getvalue()
+
+
+class TestErrorUtils:
+ def test_handle_error(self):
+ from cli_anything.lldb.utils.errors import handle_error
+
+ result = handle_error(ValueError("bad"))
+ assert result["error"] == "bad"
+ assert result["type"] == "ValueError"
+ assert "traceback" not in result
+
+ def test_handle_error_debug(self):
+ from cli_anything.lldb.utils.errors import handle_error
+
+ try:
+ raise RuntimeError("boom")
+ except RuntimeError as exc:
+ result = handle_error(exc, debug=True)
+ assert "traceback" in result
+ assert "boom" in result["traceback"]
+
+
+class TestCoreHelpers:
+ def test_breakpoints_wrapper(self):
+ from cli_anything.lldb.core.breakpoints import set_breakpoint
+
+ session = MagicMock()
+ session.breakpoint_set.return_value = {"id": 1}
+ data = set_breakpoint(session, function="main")
+ assert data["id"] == 1
+ session.breakpoint_set.assert_called_once()
+
+ def test_inspect_wrapper(self):
+ from cli_anything.lldb.core.inspect import evaluate_expression
+
+ session = MagicMock()
+ session.evaluate.return_value = {"expression": "1+1", "value": "2"}
+ data = evaluate_expression(session, "1+1")
+ assert data["value"] == "2"
+
+ def test_threads_wrapper(self):
+ from cli_anything.lldb.core.threads import list_threads
+
+ session = MagicMock()
+ session.threads.return_value = {"threads": []}
+ data = list_threads(session)
+ assert "threads" in data
+
+
+class TestCLIHelp:
+ def test_main_help(self):
+ from cli_anything.lldb.lldb_cli import cli
+
+ runner = CliRunner()
+ result = runner.invoke(cli, ["--help"])
+ assert result.exit_code == 0
+ assert "LLDB CLI" in result.output
+
+ def test_groups_help(self):
+ from cli_anything.lldb.lldb_cli import cli
+
+ runner = CliRunner()
+ for group in ("target", "process", "breakpoint", "thread", "frame", "step", "memory", "core"):
+ result = runner.invoke(cli, [group, "--help"])
+ assert result.exit_code == 0, f"{group} help failed"
+
+
+class TestCLIJsonErrors:
+ @patch("cli_anything.lldb.lldb_cli._get_session")
+ def test_target_info_no_target_json(self, mock_get_session):
+ from cli_anything.lldb.lldb_cli import cli
+
+ fake_session = MagicMock()
+ fake_session.target = None
+ mock_get_session.return_value = fake_session
+
+ runner = CliRunner()
+ result = runner.invoke(cli, ["--json", "target", "info"])
+ assert result.exit_code == 1
+ data = json.loads(result.output)
+ assert "error" in data
+
+ @patch("cli_anything.lldb.lldb_cli._get_session")
+ def test_process_info_no_process_json(self, mock_get_session):
+ from cli_anything.lldb.lldb_cli import cli
+
+ fake_session = MagicMock()
+ fake_session.target = object()
+ fake_session.process = None
+ mock_get_session.return_value = fake_session
+
+ runner = CliRunner()
+ result = runner.invoke(cli, ["--json", "process", "info"])
+ assert result.exit_code == 1
+ data = json.loads(result.output)
+ assert "error" in data
+
+
+class TestBackend:
+ @patch("cli_anything.lldb.utils.lldb_backend.subprocess.run")
+ @patch("cli_anything.lldb.utils.lldb_backend.os.path.isdir", return_value=False)
+ def test_backend_probe_failure(self, _mock_isdir, mock_run):
+ from cli_anything.lldb.utils import lldb_backend
+
+ mock_run.return_value = MagicMock(stdout="", stderr="not found")
+ with patch("builtins.__import__", side_effect=ImportError()):
+ with pytest.raises(RuntimeError):
+ lldb_backend.ensure_lldb_importable()
+
+ @patch("cli_anything.lldb.utils.lldb_backend.subprocess.run", side_effect=FileNotFoundError())
+ def test_backend_no_lldb_binary(self, _mock_run):
+ from cli_anything.lldb.utils import lldb_backend
+
+ with patch("builtins.__import__", side_effect=ImportError()):
+ with pytest.raises(RuntimeError) as exc:
+ lldb_backend.ensure_lldb_importable()
+ assert "LLDB not found" in str(exc.value)
+
+
+class TestCLISubprocess:
+ CLI_BASE = _resolve_cli("cli-anything-lldb")
+
+ def _run(self, args, check=True):
+ harness_root = str(Path(__file__).resolve().parents[3])
+ return subprocess.run(
+ self.CLI_BASE + args,
+ capture_output=True,
+ text=True,
+ check=check,
+ cwd=harness_root,
+ )
+
+ def test_cli_help_subprocess(self):
+ result = self._run(["--help"])
+ assert result.returncode == 0
+ assert "LLDB CLI" in result.stdout
diff --git a/lldb/agent-harness/cli_anything/lldb/tests/test_full_e2e.py b/lldb/agent-harness/cli_anything/lldb/tests/test_full_e2e.py
new file mode 100644
index 000000000..c9fe4072e
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/tests/test_full_e2e.py
@@ -0,0 +1,117 @@
+"""
+End-to-end tests for LLDB CLI harness.
+
+Requires LLDB installed and a test executable path in LLDB_TEST_EXE.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+HARNESS_ROOT = str(Path(__file__).resolve().parents[3])
+TEST_EXE = os.environ.get("LLDB_TEST_EXE", "")
+TEST_CORE = os.environ.get("LLDB_TEST_CORE", "")
+
+HAS_EXE = os.path.isfile(TEST_EXE) if TEST_EXE else False
+HAS_CORE = os.path.isfile(TEST_CORE) if TEST_CORE else False
+
+try:
+ import lldb # noqa: F401
+
+ HAS_LLDB_MODULE = True
+except Exception:
+ HAS_LLDB_MODULE = False
+
+skip_no_lldb = pytest.mark.skipif(not HAS_LLDB_MODULE, reason="lldb module not importable")
+skip_no_exe = pytest.mark.skipif(not HAS_EXE, reason="LLDB_TEST_EXE not set or file missing")
+skip_no_core = pytest.mark.skipif(not HAS_CORE, reason="LLDB_TEST_CORE not set or file missing")
+
+
+def _run_cli(*args) -> dict:
+ cmd = [sys.executable, "-m", "cli_anything.lldb.lldb_cli", "--json"]
+ cmd.extend(args)
+ result = subprocess.run(
+ cmd,
+ capture_output=True,
+ text=True,
+ timeout=90,
+ cwd=HARNESS_ROOT,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"CLI failed: {result.stderr}\n{result.stdout}")
+ return json.loads(result.stdout)
+
+
+@skip_no_lldb
+@skip_no_exe
+class TestLLDBE2E:
+ def test_target_create(self):
+ data = _run_cli("target", "create", "--exe", TEST_EXE)
+ assert data["executable"] == TEST_EXE
+ assert "triple" in data
+
+ def test_target_info(self):
+ # This command is stateless between invocations; verify expected error payload.
+ # Real workflow is validated in test_repl_workflow.
+ cmd = [
+ sys.executable,
+ "-m",
+ "cli_anything.lldb.lldb_cli",
+ "--json",
+ "target",
+ "info",
+ ]
+ result = subprocess.run(cmd, capture_output=True, text=True, cwd=HARNESS_ROOT)
+ assert result.returncode == 1
+ data = json.loads(result.stdout)
+ assert "error" in data
+
+ def test_repl_workflow(self):
+ script = "\n".join(
+ [
+ f"target create --exe {TEST_EXE}",
+ "process launch",
+ "process info",
+ "thread list",
+ "quit",
+ "",
+ ]
+ )
+ cmd = [sys.executable, "-m", "cli_anything.lldb.lldb_cli", "--json"]
+ result = subprocess.run(
+ cmd,
+ input=script,
+ capture_output=True,
+ text=True,
+ timeout=120,
+ cwd=HARNESS_ROOT,
+ )
+ assert result.returncode == 0
+ assert '"pid"' in result.stdout or '"error"' in result.stdout
+
+
+@skip_no_lldb
+@skip_no_exe
+@skip_no_core
+class TestCoreE2E:
+ def test_core_load_requires_target(self):
+ cmd = [
+ sys.executable,
+ "-m",
+ "cli_anything.lldb.lldb_cli",
+ "--json",
+ "core",
+ "load",
+ "--path",
+ TEST_CORE,
+ ]
+ result = subprocess.run(cmd, capture_output=True, text=True, cwd=HARNESS_ROOT)
+ assert result.returncode == 1
+ data = json.loads(result.stdout)
+ assert "error" in data
diff --git a/lldb/agent-harness/cli_anything/lldb/utils/__init__.py b/lldb/agent-harness/cli_anything/lldb/utils/__init__.py
new file mode 100644
index 000000000..69b5af5e5
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/utils/__init__.py
@@ -0,0 +1 @@
+"""Utility modules for LLDB CLI harness."""
diff --git a/lldb/agent-harness/cli_anything/lldb/utils/errors.py b/lldb/agent-harness/cli_anything/lldb/utils/errors.py
new file mode 100644
index 000000000..9d3d84c40
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/utils/errors.py
@@ -0,0 +1,26 @@
+"""
+Error handling utilities.
+"""
+
+from __future__ import annotations
+
+import sys
+import traceback
+from typing import Any, Dict
+
+
+def handle_error(e: Exception, debug: bool = False) -> Dict[str, Any]:
+ """Convert an exception into an error dict."""
+ result = {
+ "error": str(e),
+ "type": type(e).__name__,
+ }
+ if debug:
+ result["traceback"] = traceback.format_exc()
+ return result
+
+
+def die(message: str, code: int = 1):
+ """Print error message and exit."""
+ sys.stderr.write(f"Error: {message}\n")
+ sys.exit(code)
diff --git a/lldb/agent-harness/cli_anything/lldb/utils/lldb_backend.py b/lldb/agent-harness/cli_anything/lldb/utils/lldb_backend.py
new file mode 100644
index 000000000..a437283c3
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/utils/lldb_backend.py
@@ -0,0 +1,66 @@
+"""
+LLDB backend helpers: import and environment discovery for lldb Python bindings.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+
+
+def _install_hint() -> str:
+ return (
+ "LLDB not found. Install LLDB:\n"
+ " macOS: xcode-select --install\n"
+ " Ubuntu: sudo apt install lldb python3-lldb\n"
+ " Windows: winget install LLVM.LLVM\n"
+ "Then ensure 'lldb' is on PATH."
+ )
+
+
+def ensure_lldb_importable():
+ """Ensure ``lldb`` Python module can be imported.
+
+ Strategy:
+ 1) Try regular ``import lldb``
+ 2) Fallback to ``lldb -P`` to discover LLDB's Python module path
+ """
+ try:
+ import lldb # type: ignore
+
+ return lldb
+ except ImportError:
+ pass
+
+ try:
+ result = subprocess.run(
+ ["lldb", "-P"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ )
+ except FileNotFoundError as exc:
+ raise RuntimeError(_install_hint()) from exc
+ except Exception as exc: # pragma: no cover - defensive path
+ raise RuntimeError(f"Failed to probe LLDB Python path: {exc}") from exc
+
+ lldb_python_path = result.stdout.strip()
+ if lldb_python_path and os.path.isdir(lldb_python_path):
+ if lldb_python_path not in sys.path:
+ sys.path.insert(0, lldb_python_path)
+ try:
+ import lldb # type: ignore
+
+ return lldb
+ except ImportError as exc:
+ raise RuntimeError(
+ "LLDB was found but Python bindings could not be imported from:\n"
+ f" {lldb_python_path}\n"
+ "Check your LLDB installation and Python version compatibility."
+ ) from exc
+
+ stderr = result.stderr.strip()
+ detail = f"\nProbe stderr: {stderr}" if stderr else ""
+ raise RuntimeError(_install_hint() + detail)
diff --git a/lldb/agent-harness/cli_anything/lldb/utils/output.py b/lldb/agent-harness/cli_anything/lldb/utils/output.py
new file mode 100644
index 000000000..4e5b7e8ad
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/utils/output.py
@@ -0,0 +1,42 @@
+"""
+Output formatting: JSON and human-readable output helpers.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from typing import Any
+
+
+def output_json(data: Any, indent: int = 2, file=None):
+ """Write data as JSON to stdout or a file."""
+ if file is None:
+ file = sys.stdout
+ json.dump(data, file, indent=indent, default=str)
+ file.write("\n")
+
+
+def output_table(rows: list, headers: list, file=None):
+ """Print a simple ASCII table."""
+ if file is None:
+ file = sys.stdout
+
+ if not rows:
+ file.write("(no data)\n")
+ return
+
+ col_widths = [len(h) for h in headers]
+ for row in rows:
+ for i, val in enumerate(row):
+ if i < len(col_widths):
+ col_widths[i] = max(col_widths[i], len(str(val)))
+
+ header_line = " ".join(str(h).ljust(col_widths[i]) for i, h in enumerate(headers))
+ file.write(header_line + "\n")
+ file.write(" ".join("-" * w for w in col_widths) + "\n")
+
+ for row in rows:
+ truncated = row[: len(headers)]
+ line = " ".join(str(v).ljust(col_widths[i]) for i, v in enumerate(truncated))
+ file.write(line + "\n")
diff --git a/lldb/agent-harness/cli_anything/lldb/utils/repl_skin.py b/lldb/agent-harness/cli_anything/lldb/utils/repl_skin.py
new file mode 100644
index 000000000..201ff6414
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/utils/repl_skin.py
@@ -0,0 +1,525 @@
+"""cli-anything REPL Skin — Unified terminal interface for all CLI harnesses.
+
+Copy this file into your CLI package at:
+ cli_anything/<software>/utils/repl_skin.py
+
+Usage:
+ from cli_anything.<software>.utils.repl_skin import ReplSkin
+
+ skin = ReplSkin("shotcut", version="1.0.0")
+ skin.print_banner() # auto-detects skills/SKILL.md inside the package
+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)
+ skin.success("Project saved")
+ skin.error("File not found")
+ skin.warning("Unsaved changes")
+ skin.info("Processing 24 clips...")
+ skin.status("Track 1", "3 clips, 00:02:30")
+ skin.table(headers, rows)
+ skin.print_goodbye()
+"""
+
+import os
+import sys
+
+# ── ANSI color codes (no external deps for core styling) ──────────────
+
+_RESET = "\033[0m"
+_BOLD = "\033[1m"
+_DIM = "\033[2m"
+_ITALIC = "\033[3m"
+_UNDERLINE = "\033[4m"
+
+# Brand colors
+_CYAN = "\033[38;5;80m" # cli-anything brand cyan
+_CYAN_BG = "\033[48;5;80m"
+_WHITE = "\033[97m"
+_GRAY = "\033[38;5;245m"
+_DARK_GRAY = "\033[38;5;240m"
+_LIGHT_GRAY = "\033[38;5;250m"
+
+# Software accent colors — each software gets a unique accent
+_ACCENT_COLORS = {
+ "gimp": "\033[38;5;214m", # warm orange
+ "blender": "\033[38;5;208m", # deep orange
+ "inkscape": "\033[38;5;39m", # bright blue
+ "audacity": "\033[38;5;33m", # navy blue
+ "libreoffice": "\033[38;5;40m", # green
+ "obs_studio": "\033[38;5;55m", # purple
+ "kdenlive": "\033[38;5;69m", # slate blue
+ "shotcut": "\033[38;5;35m", # teal green
+}
+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue
+
+# Status colors
+_GREEN = "\033[38;5;78m"
+_YELLOW = "\033[38;5;220m"
+_RED = "\033[38;5;196m"
+_BLUE = "\033[38;5;75m"
+_MAGENTA = "\033[38;5;176m"
+
+# ── Brand icon ────────────────────────────────────────────────────────
+
+# The cli-anything icon: a small colored diamond/chevron mark
+_ICON = f"{_CYAN}{_BOLD}◆{_RESET}"
+_ICON_SMALL = f"{_CYAN}▸{_RESET}"
+
+# ── Box drawing characters ────────────────────────────────────────────
+
+_H_LINE = "─"
+_V_LINE = "│"
+_TL = "╭"
+_TR = "╮"
+_BL = "╰"
+_BR = "╯"
+_T_DOWN = "┬"
+_T_UP = "┴"
+_T_RIGHT = "├"
+_T_LEFT = "┤"
+_CROSS = "┼"
+
+
+def _strip_ansi(text: str) -> str:
+ """Remove ANSI escape codes for length calculation."""
+ import re
+
+ return re.sub(r"\033\[[^m]*m", "", text)
+
+
+def _visible_len(text: str) -> int:
+ """Get visible length of text (excluding ANSI codes)."""
+ return len(_strip_ansi(text))
+
+
+class ReplSkin:
+ """Unified REPL skin for cli-anything CLIs.
+
+ Provides consistent branding, prompts, and message formatting
+ across all CLI harnesses built with the cli-anything methodology.
+ """
+
+ def __init__(self, software: str, version: str = "1.0.0", history_file: str | None = None, skill_path: str | None = None):
+ """Initialize the REPL skin.
+
+ Args:
+ software: Software name (e.g., "gimp", "shotcut", "blender").
+ version: CLI version string.
+ history_file: Path for persistent command history.
+ Defaults to ~/.cli-anything-<software>/history
+ skill_path: Path to the SKILL.md file for agent discovery.
+ Auto-detected from the package's skills/ directory if not provided.
+ Displayed in banner for AI agents to know where to read skill info.
+ """
+ self.software = software.lower().replace("-", "_")
+ self.display_name = software.replace("_", " ").title()
+ self.version = version
+
+ # Auto-detect skill path from package layout:
+ # cli_anything/<software>/utils/repl_skin.py (this file)
+ # cli_anything/<software>/skills/SKILL.md (target)
+ if skill_path is None:
+ from pathlib import Path
+
+ _auto = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"
+ if _auto.is_file():
+ skill_path = str(_auto)
+ self.skill_path = skill_path
+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)
+
+ # History file
+ if history_file is None:
+ from pathlib import Path
+
+ hist_dir = Path.home() / f".cli-anything-{self.software}"
+ hist_dir.mkdir(parents=True, exist_ok=True)
+ self.history_file = str(hist_dir / "history")
+ else:
+ self.history_file = history_file
+
+ # Detect terminal capabilities
+ self._color = self._detect_color_support()
+
+ def _detect_color_support(self) -> bool:
+ """Check if terminal supports color."""
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):
+ return False
+ if not hasattr(sys.stdout, "isatty"):
+ return False
+ return sys.stdout.isatty()
+
+ def _c(self, code: str, text: str) -> str:
+ """Apply color code if colors are supported."""
+ if not self._color:
+ return text
+ return f"{code}{text}{_RESET}"
+
+ # ── Banner ────────────────────────────────────────────────────────
+
+ def print_banner(self):
+ """Print the startup banner with branding."""
+ inner = 54
+
+ def _box_line(content: str) -> str:
+ """Wrap content in box drawing, padding to inner width."""
+ pad = inner - _visible_len(content)
+ vl = self._c(_DARK_GRAY, _V_LINE)
+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"
+
+ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")
+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")
+
+ # Title: ◆ cli-anything · Shotcut
+ icon = self._c(_CYAN + _BOLD, "◆")
+ brand = self._c(_CYAN + _BOLD, "cli-anything")
+ dot = self._c(_DARK_GRAY, "·")
+ name = self._c(self.accent + _BOLD, self.display_name)
+ title = f" {icon} {brand} {dot} {name}"
+
+ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"
+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"
+ empty = ""
+
+ # Skill path for agent discovery
+ skill_line = None
+ if self.skill_path:
+ skill_icon = self._c(_MAGENTA, "◇")
+ skill_label = self._c(_DARK_GRAY, " Skill:")
+ skill_path_display = self._c(_LIGHT_GRAY, self.skill_path)
+ skill_line = f" {skill_icon} {skill_label} {skill_path_display}"
+
+ print(top)
+ print(_box_line(title))
+ print(_box_line(ver))
+ if skill_line:
+ print(_box_line(skill_line))
+ print(_box_line(empty))
+ print(_box_line(tip))
+ print(bot)
+ print()
+
+ # ── Prompt ────────────────────────────────────────────────────────
+
+ def prompt(self, project_name: str = "", modified: bool = False, context: str = "") -> str:
+ """Build a styled prompt string for prompt_toolkit or input().
+
+ Args:
+ project_name: Current project name (empty if none open).
+ modified: Whether the project has unsaved changes.
+ context: Optional extra context to show in prompt.
+
+ Returns:
+ Formatted prompt string.
+ """
+ parts = []
+
+ # Icon
+ if self._color:
+ parts.append(f"{_CYAN}◆{_RESET} ")
+ else:
+ parts.append("> ")
+
+ # Software name
+ parts.append(self._c(self.accent + _BOLD, self.software))
+
+ # Project context
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ parts.append(f" {self._c(_DARK_GRAY, '[')}")
+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))
+ parts.append(self._c(_DARK_GRAY, ']'))
+
+ parts.append(self._c(_GRAY, " ❯ "))
+
+ return "".join(parts)
+
+ def prompt_tokens(self, project_name: str = "", modified: bool = False, context: str = ""):
+ """Build prompt_toolkit formatted text tokens for the prompt.
+
+ Use with prompt_toolkit's FormattedText for proper ANSI handling.
+
+ Returns:
+ list of (style, text) tuples for prompt_toolkit.
+ """
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+ tokens = []
+
+ tokens.append(("class:icon", "◆ "))
+ tokens.append(("class:software", self.software))
+
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ tokens.append(("class:bracket", " ["))
+ tokens.append(("class:context", f"{ctx}{mod}"))
+ tokens.append(("class:bracket", "]"))
+
+ tokens.append(("class:arrow", " ❯ "))
+
+ return tokens
+
+ def get_prompt_style(self):
+ """Get a prompt_toolkit Style object matching the skin.
+
+ Returns:
+ prompt_toolkit.styles.Style
+ """
+ try:
+ from prompt_toolkit.styles import Style
+ except ImportError:
+ return None
+
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+
+ return Style.from_dict(
+ {
+ "icon": "#5fdfdf bold", # cyan brand color
+ "software": f"{accent_hex} bold",
+ "bracket": "#585858",
+ "context": "#bcbcbc",
+ "arrow": "#808080",
+ # Completion menu
+ "completion-menu.completion": "bg:#303030 #bcbcbc",
+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",
+ "completion-menu.meta.completion": "bg:#303030 #808080",
+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",
+ # Auto-suggest
+ "auto-suggest": "#585858",
+ # Bottom toolbar
+ "bottom-toolbar": "bg:#1c1c1c #808080",
+ "bottom-toolbar.text": "#808080",
+ }
+ )
+
+ # ── Messages ──────────────────────────────────────────────────────
+
+ def success(self, message: str):
+ """Print a success message with green checkmark."""
+ icon = self._c(_GREEN + _BOLD, "✓")
+ print(f" {icon} {self._c(_GREEN, message)}")
+
+ def error(self, message: str):
+ """Print an error message with red cross."""
+ icon = self._c(_RED + _BOLD, "✗")
+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)
+
+ def warning(self, message: str):
+ """Print a warning message with yellow triangle."""
+ icon = self._c(_YELLOW + _BOLD, "⚠")
+ print(f" {icon} {self._c(_YELLOW, message)}")
+
+ def info(self, message: str):
+ """Print an info message with blue dot."""
+ icon = self._c(_BLUE, "●")
+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")
+
+ def hint(self, message: str):
+ """Print a subtle hint message."""
+ print(f" {self._c(_DARK_GRAY, message)}")
+
+ def section(self, title: str):
+ """Print a section header."""
+ print()
+ print(f" {self._c(self.accent + _BOLD, title)}")
+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")
+
+ # ── Status display ────────────────────────────────────────────────
+
+ def status(self, label: str, value: str):
+ """Print a key-value status line."""
+ lbl = self._c(_GRAY, f" {label}:")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def status_block(self, items: dict[str, str], title: str = ""):
+ """Print a block of status key-value pairs.
+
+ Args:
+ items: Dict of label -> value pairs.
+ title: Optional title for the block.
+ """
+ if title:
+ self.section(title)
+
+ max_key = max(len(k) for k in items) if items else 0
+ for label, value in items.items():
+ lbl = self._c(_GRAY, f" {label:<{max_key}}")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def progress(self, current: int, total: int, label: str = ""):
+ """Print a simple progress indicator.
+
+ Args:
+ current: Current step number.
+ total: Total number of steps.
+ label: Optional label for the progress.
+ """
+ pct = int(current / total * 100) if total > 0 else 0
+ bar_width = 20
+ filled = int(bar_width * current / total) if total > 0 else 0
+ bar = "█" * filled + "░" * (bar_width - filled)
+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"
+ if label:
+ text += f" {self._c(_LIGHT_GRAY, label)}"
+ print(text)
+
+ # ── Table display ─────────────────────────────────────────────────
+
+ def table(self, headers: list[str], rows: list[list[str]], max_col_width: int = 40):
+ """Print a formatted table with box-drawing characters.
+
+ Args:
+ headers: Column header strings.
+ rows: List of rows, each a list of cell strings.
+ max_col_width: Maximum column width before truncation.
+ """
+ if not headers:
+ return
+
+ # Calculate column widths
+ col_widths = [min(len(h), max_col_width) for h in headers]
+ for row in rows:
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ col_widths[i] = min(max(col_widths[i], len(str(cell))), max_col_width)
+
+ def pad(text: str, width: int) -> str:
+ t = str(text)[:width]
+ return t + " " * (width - len(t))
+
+ # Header
+ header_cells = [self._c(_CYAN + _BOLD, pad(h, col_widths[i])) for i, h in enumerate(headers)]
+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ header_line = f" {sep.join(header_cells)}"
+ print(header_line)
+
+ # Separator
+ sep_line = self._c(_DARK_GRAY, f" {'───'.join([_H_LINE * w for w in col_widths])}")
+ print(sep_line)
+
+ # Rows
+ for row in rows:
+ cells = []
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))
+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ print(f" {row_sep.join(cells)}")
+
+ # ── Help display ──────────────────────────────────────────────────
+
+ def help(self, commands: dict[str, str]):
+ """Print a formatted help listing.
+
+ Args:
+ commands: Dict of command -> description pairs.
+ """
+ self.section("Commands")
+ max_cmd = max(len(c) for c in commands) if commands else 0
+ for cmd, desc in commands.items():
+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")
+ desc_styled = self._c(_GRAY, f" {desc}")
+ print(f"{cmd_styled}{desc_styled}")
+ print()
+
+ # ── Goodbye ───────────────────────────────────────────────────────
+
+ def print_goodbye(self):
+ """Print a styled goodbye message."""
+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")
+
+ # ── Prompt toolkit session factory ────────────────────────────────
+
+ def create_prompt_session(self):
+ """Create a prompt_toolkit PromptSession with skin styling.
+
+ Returns:
+ A configured PromptSession, or None if prompt_toolkit unavailable.
+ """
+ # prompt_toolkit's Windows console backend requires a real TTY/console
+ # handle. When the CLI is driven by subprocess pipes for tests or agent
+ # automation, fall back to plain input() instead of crashing.
+ if not getattr(sys.stdin, "isatty", lambda: False)():
+ return None
+ if not getattr(sys.stdout, "isatty", lambda: False)():
+ return None
+
+ try:
+ from prompt_toolkit import PromptSession
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
+ from prompt_toolkit.history import FileHistory
+
+ style = self.get_prompt_style()
+
+ session = PromptSession(
+ history=FileHistory(self.history_file),
+ auto_suggest=AutoSuggestFromHistory(),
+ style=style,
+ enable_history_search=True,
+ )
+ return session
+ except ImportError:
+ return None
+
+ def get_input(self, pt_session, project_name: str = "", modified: bool = False, context: str = "") -> str:
+ """Get input from user using prompt_toolkit or fallback.
+
+ Args:
+ pt_session: A prompt_toolkit PromptSession (or None).
+ project_name: Current project name.
+ modified: Whether project has unsaved changes.
+ context: Optional context string.
+
+ Returns:
+ User input string (stripped).
+ """
+ if pt_session is not None:
+ from prompt_toolkit.formatted_text import FormattedText
+
+ tokens = self.prompt_tokens(project_name, modified, context)
+ return pt_session.prompt(FormattedText(tokens)).strip()
+ raw_prompt = self.prompt(project_name, modified, context)
+ return input(raw_prompt).strip()
+
+ # ── Toolbar builder ───────────────────────────────────────────────
+
+ def bottom_toolbar(self, items: dict[str, str]):
+ """Create a bottom toolbar callback for prompt_toolkit.
+
+ Args:
+ items: Dict of label -> value pairs to show in toolbar.
+
+ Returns:
+ A callable that returns FormattedText for the toolbar.
+ """
+
+ def toolbar():
+ from prompt_toolkit.formatted_text import FormattedText
+
+ parts = []
+ for i, (k, v) in enumerate(items.items()):
+ if i > 0:
+ parts.append(("class:bottom-toolbar.text", " │ "))
+ parts.append(("class:bottom-toolbar.text", f" {k}: "))
+ parts.append(("class:bottom-toolbar", v))
+ return FormattedText(parts)
+
+ return toolbar
+
+
+# ── ANSI 256-color to hex mapping (for prompt_toolkit styles) ─────────
+
+_ANSI_256_TO_HEX = {
+ "\033[38;5;33m": "#0087ff", # audacity navy blue
+ "\033[38;5;35m": "#00af5f", # shotcut teal
+ "\033[38;5;39m": "#00afff", # inkscape bright blue
+ "\033[38;5;40m": "#00d700", # libreoffice green
+ "\033[38;5;55m": "#5f00af", # obs purple
+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue
+ "\033[38;5;75m": "#5fafff", # default sky blue
+ "\033[38;5;80m": "#5fd7d7", # brand cyan
+ "\033[38;5;208m": "#ff8700", # blender deep orange
+ "\033[38;5;214m": "#ffaf00", # gimp warm orange
+}
diff --git a/lldb/agent-harness/setup.py b/lldb/agent-harness/setup.py
new file mode 100644
index 000000000..bbf8c2232
--- /dev/null
+++ b/lldb/agent-harness/setup.py
@@ -0,0 +1,41 @@
+"""Setup for cli-anything-lldb package."""
+
+from pathlib import Path
+
+from setuptools import find_namespace_packages, setup
+
+_README = Path(__file__).parent / "cli_anything" / "lldb" / "README.md"
+_long_desc = _README.read_text(encoding="utf-8") if _README.is_file() else ""
+
+setup(
+ name="cli-anything-lldb",
+ version="0.1.0",
+ description="CLI harness for LLDB debugger via Python API",
+ 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-lldb=cli_anything.lldb.lldb_cli:main",
+ ],
+ },
+ package_data={
+ "cli_anything.lldb": ["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.json
index b20c870f7..e410a6ec2 100644
--- a/registry.json
+++ b/registry.json
@@ -173,6 +173,20 @@
"contributor": "CLI-Anything-Team",
"contributor_url": "https://github.com/HKUDS/CLI-Anything"
},
+ {
+ "name": "lldb",
+ "display_name": "LLDB",
+ "version": "0.1.0",
+ "description": "Stateful native debugging via the LLDB Python API with JSON-friendly inspection commands",
+ "requires": "LLDB installation with Python bindings available (for example LLVM.LLVM on Windows)",
+ "homepage": "https://lldb.llvm.org",
+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=lldb/agent-harness",
+ "entry_point": "cli-anything-lldb",
+ "skill_md": "lldb/agent-harness/cli_anything/lldb/skills/SKILL.md",
+ "category": "debugging",
+ "contributor": "AiMiDi",
+ "contributor_url": "https://github.com/AiMiDi"
+ },
{
"name": "zotero",
"display_name": "Zotero",