Skip to content

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

Python

fix: harden lldb session workflows

aimidi0114d60ee0c3
diff --git a/README.md b/README.md
index 0c028cba9..3670e3665 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@ CLI-Anything: Bridging the Gap Between AI Agents and the World's Software</stron
<a href="#-quick-start"><img src="https://img.shields.io/badge/Quick_Start-5_min-blue?style=for-the-badge" alt="Quick Start"></a>
<a href="https://hkuds.github.io/CLI-Anything/"><img src="https://img.shields.io/badge/CLI_Hub-Browse_%26_Install-ff69b4?style=for-the-badge" alt="CLI Hub"></a>
<a href="#-demonstrations"><img src="https://img.shields.io/badge/Demos-31_Apps-green?style=for-the-badge" alt="Demos"></a>
- <a href="#-test-results"><img src="https://img.shields.io/badge/Tests-2%2C173_Passing-brightgreen?style=for-the-badge" alt="Tests"></a>
+ <a href="#-test-results"><img src="https://img.shields.io/badge/Tests-2%2C179_Passing-brightgreen?style=for-the-badge" alt="Tests"></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow?style=for-the-badge" alt="License"></a>
</p>
@@ -595,7 +595,7 @@ AI agents are great at reasoning but terrible at using real professional softwar
| ๐Ÿ’ธ "UI automation breaks constantly" | No screenshots, no clicking, no RPA fragility. Pure command-line reliability with structured interfaces |
| ๐Ÿ“Š "Agents need structured data" | Built-in JSON output for seamless agent consumption + human-readable formats for debugging |
| ๐Ÿ”ง "Custom integrations are expensive" | One Claude plugin auto-generates CLIs for ANY codebase through proven 7-phase pipeline |
-| โšก "Prototype vs Production gap" | 2,173+ tests with real software validation. Battle-tested across 31 major applications |
+| โšก "Prototype vs Production gap" | 2,179+ tests with real software validation. Battle-tested across 31 major applications |
---
@@ -887,7 +887,7 @@ Each application received complete, production-ready CLI interfaces โ€” not demo
<td>Native Debugging</td>
<td><code>cli-anything-lldb</code></td>
<td>LLDB Python API</td>
-<td align="center">โœ… 21</td>
+<td align="center">โœ… 27</td>
</tr>
<tr>
<td align="center"><strong>โ›“๏ธ ETH2 QuickStart</strong></td>
@@ -996,11 +996,11 @@ Each application received complete, production-ready CLI interfaces โ€” not demo
</tr>
<tr>
<td align="center" colspan="4"><strong>Total</strong></td>
-<td align="center"><strong>โœ… 2,173</strong></td>
+<td align="center"><strong>โœ… 2,179</strong></td>
</tr>
</table>
-> **100% pass rate** across all 2,173 tests โ€” 1,582 unit tests + 572 end-to-end tests + 19 Node.js tests.
+> **100% pass rate** across all 2,179 tests โ€” 1,587 unit tests + 573 end-to-end tests + 19 Node.js tests.
---
@@ -1028,7 +1028,7 @@ kdenlive 155 passed โœ… (111 unit + 44 e2e)
shotcut 154 passed โœ… (110 unit + 44 e2e)
zoom 22 passed โœ… (22 unit + 0 e2e)
drawio 138 passed โœ… (116 unit + 22 e2e)
-lldb 21 passed โœ… (18 unit + 3 e2e, 1 core e2e skipped)
+lldb 27 passed โœ… (23 unit + 4 e2e)
eth2-quickstart 18 passed โœ… (18 unit + 3 e2e skipped)
mermaid 10 passed โœ… (5 unit + 5 e2e)
anygen 50 passed โœ… (40 unit + 10 e2e)
@@ -1042,7 +1042,7 @@ cloudcompare 88 passed โœ… (49 unit + 39 e2e)
openscreen 101 passed โœ… (78 unit + 23 e2e)
cloudanalyzer 14 passed โœ… (7 unit + 7 e2e)
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
-TOTAL 2,173 passed โœ… 100% pass rate
+TOTAL 2,179 passed โœ… 100% pass rate
```
---
@@ -1116,7 +1116,7 @@ cli-anything/
โ”œโ”€โ”€ ๐ŸŽฎ godot/agent-harness/ # Godot Engine CLI (24 tests)
โ”œโ”€โ”€ ๐ŸŽจ sketch/agent-harness/ # Sketch CLI (19 tests, Node.js)
โ”œโ”€โ”€ ๐Ÿ”ฌ renderdoc/agent-harness/ # RenderDoc CLI (59 tests)
-โ”œโ”€โ”€ ๐Ÿž lldb/agent-harness/ # LLDB CLI (21 tests)
+โ”œโ”€โ”€ ๐Ÿž lldb/agent-harness/ # LLDB CLI (27 tests)
โ”œโ”€โ”€ ๐ŸŽฌ videocaptioner/agent-harness/ # VideoCaptioner CLI (26 tests)
โ”œโ”€โ”€ ๐ŸŽฌ openscreen/agent-harness/ # Openscreen CLI โ€” screen recording editor (101 tests)
โ”œโ”€โ”€ โ˜๏ธ cloudcompare/agent-harness/ # CloudCompare CLI (88 tests)
@@ -1347,7 +1347,7 @@ MIT License โ€” free to use, modify, and distribute.
**CLI-Anything** โ€” *Make any software with a codebase Agent-native.*
-<sub>A methodology for the age of AI agents | 31 professional software demos | 2,173 passing tests</sub>
+<sub>A methodology for the age of AI agents | 31 professional software demos | 2,179 passing tests</sub>
<br>
diff --git a/README_CN.md b/README_CN.md
index 9b584d335..9122e2f97 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -375,7 +375,7 @@ AI Agent ๆŽจ็†่ƒฝๅŠ›ๅพˆๅผบ๏ผŒไฝ†ๆ“ๆŽง็œŸๅฎžไธ“ไธš่ฝฏไปถ็š„่ƒฝๅŠ›ๅพˆๅผฑใ€‚็Žฐ
| ๐Ÿ’ธ "GUI ่‡ชๅŠจๅŒ–ไธ‰ๅคฉไธคๅคดๅดฉ" | ๅ‘Šๅˆซๆˆชๅ›พใ€็‚นๅ‡ปๅ’Œ RPA ็š„่„†ๅผฑๆ€ง๏ผŒ็บฏๅ‘ฝไปค่กŒๆ“ๆŽง๏ผŒ็ป“ๆž„ๅŒ–ๆŽฅๅฃ |
| ๐Ÿ“Š "Agent ้œ€่ฆ็ป“ๆž„ๅŒ–ๆ•ฐๆฎ" | ๅ†…็ฝฎ JSON ่พ“ๅ‡บไพ› Agent ็›ดๆŽฅๆถˆ่ดน๏ผŒๅŒๆ—ถไฟ็•™ๅฏ่ฏปๆ ผๅผๆ–นไพฟ่ฐƒ่ฏ• |
| ๐Ÿ”ง "ๅฎšๅˆถ้›†ๆˆๅคช่ดตไบ†" | ไธ€ไธชๆ’ไปถๅฐฑ่ƒฝไธบไปปๆ„ไปฃ็ ๅบ“่‡ชๅŠจ็”Ÿๆˆ CLI๏ผŒ็ป่ฟ‡้ชŒ่ฏ็š„ 7 ้˜ถๆฎตๆตๆฐด็บฟ |
-| โšก "ๅŽŸๅž‹ๅ’Œ็”Ÿไบงไน‹้—ดๅทฎๅไธ‡ๅ…ซๅƒ้‡Œ" | 1,649+ ๆต‹่ฏ•็”จไพ‹๏ผŒๅ…จ้ƒจๅœจ็œŸๅฎž่ฝฏไปถไธŠ้ชŒ่ฏ้€š่ฟ‡๏ผŒ่ฆ†็›– 15 ๆฌพไธปๆตๅบ”็”จ |
+| โšก "ๅŽŸๅž‹ๅ’Œ็”Ÿไบงไน‹้—ดๅทฎๅไธ‡ๅ…ซๅƒ้‡Œ" | 1,655+ ๆต‹่ฏ•็”จไพ‹๏ผŒๅ…จ้ƒจๅœจ็œŸๅฎž่ฝฏไปถไธŠ้ชŒ่ฏ้€š่ฟ‡๏ผŒ่ฆ†็›– 15 ๆฌพไธปๆตๅบ”็”จ |
---
@@ -579,7 +579,7 @@ CLI-Anything ้€‚็”จไบŽไปปไฝ•ๆœ‰ไปฃ็ ๅบ“็š„่ฝฏไปถ โ€”โ€” ไธ้™้ข†ๅŸŸ๏ผŒไธ้™
<td>ๅŽŸ็”Ÿ่ฐƒ่ฏ•</td>
<td><code>cli-anything-lldb</code></td>
<td>LLDB Python API</td>
-<td align="center">โœ… 21</td>
+<td align="center">โœ… 27</td>
</tr>
<tr>
<td align="center"><strong>โœจ AnyGen</strong></td>
@@ -597,11 +597,11 @@ CLI-Anything ้€‚็”จไบŽไปปไฝ•ๆœ‰ไปฃ็ ๅบ“็š„่ฝฏไปถ โ€”โ€” ไธ้™้ข†ๅŸŸ๏ผŒไธ้™
</tr>
<tr>
<td align="center" colspan="4"><strong>ๅˆ่ฎก</strong></td>
-<td align="center"><strong>โœ… 1,649</strong></td>
+<td align="center"><strong>โœ… 1,655</strong></td>
</tr>
</table>
-> ๅ…จ้ƒจ 1,649 ้กนๆต‹่ฏ• **100% ้€š่ฟ‡** โ€”โ€” 1,169 ้กนๅ•ๅ…ƒๆต‹่ฏ• + 461 ้กน็ซฏๅˆฐ็ซฏๆต‹่ฏ• + 19 ้กน Node.js ๆต‹่ฏ•ใ€‚
+> ๅ…จ้ƒจ 1,655 ้กนๆต‹่ฏ• **100% ้€š่ฟ‡** โ€”โ€” 1,174 ้กนๅ•ๅ…ƒๆต‹่ฏ• + 462 ้กน็ซฏๅˆฐ็ซฏๆต‹่ฏ• + 19 ้กน Node.js ๆต‹่ฏ•ใ€‚
---
@@ -629,11 +629,11 @@ shotcut 154 passed โœ… (110 unit + 44 e2e)
openscreen 101 passed โœ… (78 unit + 23 e2e)
zoom 22 passed โœ… (22 unit + 0 e2e)
drawio 138 passed โœ… (116 unit + 22 e2e)
-lldb 21 passed โœ… (18 unit + 3 e2e, 1 core e2e skipped)
+lldb 27 passed โœ… (23 unit + 4 e2e)
anygen 50 passed โœ… (40 unit + 10 e2e)
sketch 19 passed โœ… (19 jest, Node.js)
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
-TOTAL 1,649 passed โœ… 100% pass rate
+TOTAL 1,655 passed โœ… 100% pass rate
```
---
@@ -699,7 +699,7 @@ cli-anything/
โ”œโ”€โ”€ ๐ŸŽฌ openscreen/agent-harness/ # Openscreen CLI โ€” ๅฑๅน•ๅฝ•ๅƒ็ผ–่พ‘ๅ™จ๏ผˆ101 ้กนๆต‹่ฏ•๏ผ‰
โ”œโ”€โ”€ ๐Ÿ“ž zoom/agent-harness/ # Zoom CLI๏ผˆ22 ้กนๆต‹่ฏ•๏ผ‰
โ”œโ”€โ”€ ๐Ÿ“ drawio/agent-harness/ # Draw.io CLI๏ผˆ138 ้กนๆต‹่ฏ•๏ผ‰
-โ”œโ”€โ”€ ๐Ÿž lldb/agent-harness/ # LLDB CLI๏ผˆ21 ้กนๆต‹่ฏ•๏ผ‰
+โ”œโ”€โ”€ ๐Ÿž lldb/agent-harness/ # LLDB CLI๏ผˆ27 ้กนๆต‹่ฏ•๏ผ‰
โ”œโ”€โ”€ โœจ anygen/agent-harness/ # AnyGen CLI๏ผˆ50 ้กนๆต‹่ฏ•๏ผ‰
โ””โ”€โ”€ ๐ŸŽจ sketch/agent-harness/ # Sketch CLI๏ผˆ19 ้กนๆต‹่ฏ•๏ผŒNode.js๏ผ‰
```
@@ -937,7 +937,7 @@ MIT License โ€” ๅฏ่‡ช็”ฑไฝฟ็”จใ€ไฟฎๆ”นๅ’Œๅˆ†ๅ‘ใ€‚
**CLI-Anything** โ€” *ไธ€่กŒๅ‘ฝไปค๏ผŒ่ฎฉไปปไฝ•่ฝฏไปถๆˆไธบ Agent ็š„ๅŽŸ็”Ÿๅทฅๅ…ทใ€‚*
-<sub>ไธบ AI Agent ๆ—ถไปฃ่€Œ็”Ÿ | 15 ๆฌพไธ“ไธš่ฝฏไปถๅฎžๆต‹ | 1,649 ้กนๆต‹่ฏ•ๅ…จ้ƒจ้€š่ฟ‡</sub>
+<sub>ไธบ AI Agent ๆ—ถไปฃ่€Œ็”Ÿ | 15 ๆฌพไธ“ไธš่ฝฏไปถๅฎžๆต‹ | 1,655 ้กนๆต‹่ฏ•ๅ…จ้ƒจ้€š่ฟ‡</sub>
<br>
diff --git a/lldb/agent-harness/cli_anything/lldb/README.md b/lldb/agent-harness/cli_anything/lldb/README.md
index b3463e7ff..2c93d8894 100644
--- a/lldb/agent-harness/cli_anything/lldb/README.md
+++ b/lldb/agent-harness/cli_anything/lldb/README.md
@@ -65,6 +65,10 @@ such as `target create`, `breakpoint set`, `process launch`, and follow-up
inspection commands can run as separate CLI invocations against the same live
debugger state.
+The persistent session daemon now speaks a localhost JSON socket protocol and
+stores its session token in an owner-scoped state file. `memory find` scans in
+64 KiB chunks and caps each request at 1 MiB.
+
## Command Groups
- `target`: `create`, `info`
@@ -98,3 +102,4 @@ pytest cli_anything/lldb/tests/test_full_e2e.py -v
E2E tests require:
- a working C compiler (`clang`, `gcc`, or `cc`) so the tests can build a small debug helper
- no extra env vars for the default suite; `LLDB_TEST_CORE` is optional if you want to point the negative-path core-load check at a specific local file
+- `memory find` scans are chunked and capped at 1 MiB per invocation
diff --git a/lldb/agent-harness/cli_anything/lldb/core/session.py b/lldb/agent-harness/cli_anything/lldb/core/session.py
index 7918c6f90..e6c304f82 100644
--- a/lldb/agent-harness/cli_anything/lldb/core/session.py
+++ b/lldb/agent-harness/cli_anything/lldb/core/session.py
@@ -9,6 +9,9 @@ from typing import Any, Dict, List, Optional
from cli_anything.lldb.utils.lldb_backend import ensure_lldb_importable
+MEMORY_FIND_MAX_SCAN_SIZE = 1024 * 1024
+MEMORY_FIND_CHUNK_SIZE = 64 * 1024
+
class LLDBSession:
"""Encapsulates one LLDB debugger session using Python API only."""
@@ -62,13 +65,9 @@ class LLDBSession:
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}")
- self._process_origin = "attached"
- return self._process_info()
+ attach_info = self._lldb.SBAttachInfo()
+ attach_info.SetProcessID(pid)
+ return self._attach(attach_info)
def attach_name(self, name: str, wait_for: bool = False) -> Dict[str, Any]:
self._require_target()
@@ -76,12 +75,15 @@ class LLDBSession:
attach_info.SetExecutable(name)
if wait_for:
attach_info.SetWaitForLaunch(True, False)
+ return self._attach(attach_info)
+
+ def _attach(self, attach_info) -> Dict[str, Any]:
error = self._lldb.SBError()
self.process = self.target.Attach(attach_info, error)
if not error.Success():
raise RuntimeError(f"Attach failed: {error}")
self._process_origin = "attached"
- return self._process_info()
+ return self.process_info()
def launch(
self,
@@ -94,7 +96,7 @@ class LLDBSession:
if not self.process or not self.process.IsValid():
raise RuntimeError("Launch failed")
self._process_origin = "launched"
- return self._process_info()
+ return self.process_info()
def detach(self) -> Dict[str, Any]:
self._require_process()
@@ -175,6 +177,9 @@ class LLDBSession:
def continue_exec(self) -> Dict[str, Any]:
self._require_process()
self.process.Continue()
+ return self.process_info()
+
+ def process_info(self) -> Dict[str, Any]:
return self._process_info()
def backtrace(self, limit: int = 50) -> Dict[str, Any]:
@@ -276,13 +281,71 @@ class LLDBSession:
"hex": data.hex(),
}
+ def find_memory(
+ self,
+ needle: str,
+ start_address: int,
+ size: int,
+ *,
+ chunk_size: int = MEMORY_FIND_CHUNK_SIZE,
+ max_scan_size: int = MEMORY_FIND_MAX_SCAN_SIZE,
+ ) -> Dict[str, Any]:
+ self._require_process()
+ if not needle:
+ raise ValueError("Needle must not be empty")
+ if size <= 0:
+ raise ValueError("Scan size must be positive")
+ if size > max_scan_size:
+ raise ValueError(
+ f"Scan size exceeds max supported scan size ({max_scan_size} bytes)"
+ )
+ if chunk_size <= 0:
+ raise ValueError("Chunk size must be positive")
+
+ needle_bytes = needle.encode("utf-8")
+ overlap = max(0, len(needle_bytes) - 1)
+ remaining = size
+ current = start_address
+ trailing = b""
+
+ while remaining > 0:
+ read_size = min(chunk_size, remaining)
+ chunk = bytes.fromhex(self.read_memory(current, read_size)["hex"])
+ haystack = trailing + chunk
+ idx = haystack.find(needle_bytes)
+ if idx >= 0:
+ base = current - len(trailing)
+ return {
+ "needle": needle,
+ "start": hex(start_address),
+ "size": size,
+ "found": True,
+ "address": hex(base + idx),
+ "chunk_size": chunk_size,
+ "max_scan_size": max_scan_size,
+ }
+
+ trailing = haystack[-overlap:] if overlap else b""
+ current += read_size
+ remaining -= read_size
+
+ return {
+ "needle": needle,
+ "start": hex(start_address),
+ "size": size,
+ "found": False,
+ "address": None,
+ "chunk_size": chunk_size,
+ "max_scan_size": max_scan_size,
+ }
+
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}")
self._process_origin = "core"
- return self._process_info()
+ return self.process_info()
def destroy(self):
if self.process and self.process.IsValid():
diff --git a/lldb/agent-harness/cli_anything/lldb/lldb_cli.py b/lldb/agent-harness/cli_anything/lldb/lldb_cli.py
index b5fed5c11..ae5b97b2d 100644
--- a/lldb/agent-harness/cli_anything/lldb/lldb_cli.py
+++ b/lldb/agent-harness/cli_anything/lldb/lldb_cli.py
@@ -11,6 +11,7 @@ import shlex
from typing import Optional
import click
+from cli_anything.lldb.core.session import MEMORY_FIND_MAX_SCAN_SIZE
_session = None # type: ignore
_session_file = None
@@ -248,7 +249,7 @@ def process_detach(ctx):
def process_info(ctx):
"""Show process status."""
try:
- data = _require_process()._process_info()
+ data = _require_process().process_info()
_output(ctx, data)
except Exception as exc:
_handle_exc(ctx, exc)
@@ -383,7 +384,9 @@ def thread_info(ctx):
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"})
+ if selected is None:
+ raise RuntimeError("No selected thread")
+ _output(ctx, selected)
except Exception as exc:
_handle_exc(ctx, exc)
@@ -520,22 +523,18 @@ def memory_read(ctx, address: str, size: int):
@memory_group.command("find")
@click.argument("needle", required=True, type=str)
@click.option("--start", "start_addr", required=True, type=str, help="Start address (hex/int).")
[email protected]("--size", required=True, type=int, help="Scan size in bytes.")
+ "--size",
+ required=True,
+ type=int,
+ help=f"Scan size in bytes (chunked scan, max {MEMORY_FIND_MAX_SCAN_SIZE} bytes).",
+)
@click.pass_context
def memory_find(ctx, needle: str, start_addr: str, size: int):
- """Find ASCII needle in memory region (naive scan)."""
+ """Find a UTF-8 needle in memory using a chunked 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,
- }
+ data = _require_process().find_memory(needle, addr_val, size)
_output(ctx, data)
except Exception as exc:
_handle_exc(ctx, exc)
diff --git a/lldb/agent-harness/cli_anything/lldb/skills/SKILL.md b/lldb/agent-harness/cli_anything/lldb/skills/SKILL.md
index 9a0a95d82..08afc4727 100644
--- a/lldb/agent-harness/cli_anything/lldb/skills/SKILL.md
+++ b/lldb/agent-harness/cli_anything/lldb/skills/SKILL.md
@@ -94,9 +94,10 @@ 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:
+- Non-REPL commands share state across separate invocations through the persistent session daemon until you run `session close` or the idle timeout expires.
+- Use REPL when you want an interactive long-running debugger session:
- run `cli-anything-lldb`
- execute multi-step commands in one session
+- `memory find` uses a chunked scan capped at 1 MiB per call.
- 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
index 4d10782ea..4a633a300 100644
--- a/lldb/agent-harness/cli_anything/lldb/tests/TEST.md
+++ b/lldb/agent-harness/cli_anything/lldb/tests/TEST.md
@@ -96,9 +96,9 @@ python -m pytest cli_anything/lldb/tests -q
### Result summary
-- `test_core.py`: 18 passed
+- `test_core.py`: 23 passed
- `test_full_e2e.py`: 4 passed
-- combined: 22 passed
+- combined: 27 passed
### Notes
@@ -107,4 +107,6 @@ python -m pytest cli_anything/lldb/tests -q
- 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
- Added a persistent background LLDB session so non-REPL commands can share debugger state
+- Switched the session daemon to a localhost JSON socket protocol with owner-scoped state file permissions
+- `memory find` now uses a chunked scan capped at 1 MiB per call
- Fixed cleanup to detach attached inferiors instead of killing them on session shutdown
diff --git a/lldb/agent-harness/cli_anything/lldb/tests/test_core.py b/lldb/agent-harness/cli_anything/lldb/tests/test_core.py
index 20db279f9..61ca867f2 100644
--- a/lldb/agent-harness/cli_anything/lldb/tests/test_core.py
+++ b/lldb/agent-harness/cli_anything/lldb/tests/test_core.py
@@ -140,6 +140,38 @@ class TestCLIJsonErrors:
data = json.loads(result.output)
assert "error" in data
+ @patch("cli_anything.lldb.lldb_cli._get_session")
+ def test_thread_info_no_selected_thread_json(self, mock_get_session):
+ from cli_anything.lldb.lldb_cli import cli
+
+ fake_session = MagicMock()
+ fake_session.session_status.return_value = {"has_target": True, "has_process": True}
+ fake_session.threads.return_value = {"threads": [{"id": 1, "selected": False}]}
+ mock_get_session.return_value = fake_session
+
+ runner = CliRunner()
+ result = runner.invoke(cli, ["--json", "thread", "info"])
+ assert result.exit_code == 1
+ data = json.loads(result.output)
+ assert data["error"] == "No selected thread"
+
+ @patch("cli_anything.lldb.lldb_cli._get_session")
+ def test_process_info_uses_public_session_api(self, mock_get_session):
+ from cli_anything.lldb.lldb_cli import cli
+
+ fake_session = MagicMock()
+ fake_session.session_status.return_value = {"has_target": True, "has_process": True}
+ fake_session.process_info.return_value = {"pid": 1234, "state": "stopped", "num_threads": 1}
+ fake_session._process_info.side_effect = AssertionError("private API should not be used")
+ mock_get_session.return_value = fake_session
+
+ runner = CliRunner()
+ result = runner.invoke(cli, ["--json", "process", "info"])
+ assert result.exit_code == 0
+ data = json.loads(result.output)
+ assert data["pid"] == 1234
+ fake_session.process_info.assert_called_once_with()
+
@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
@@ -238,6 +270,57 @@ class TestSessionLifecycle:
assert status["has_process"] is True
assert status["process_origin"] == "attached"
+ def test_process_info_public_wrapper(self):
+ from cli_anything.lldb.core.session import LLDBSession
+
+ session = self._make_session()
+ process = MagicMock()
+ process.IsValid.return_value = True
+ process.GetProcessID.return_value = 77
+ process.GetState.return_value = 5
+ process.GetNumThreads.return_value = 2
+ session.process = process
+
+ data = LLDBSession.process_info(session)
+
+ assert data == {"pid": 77, "state": "stopped", "num_threads": 2}
+
+ def test_find_memory_scans_in_chunks(self):
+ from cli_anything.lldb.core.session import LLDBSession
+
+ session = self._make_session()
+ process = MagicMock()
+ process.IsValid.return_value = True
+ session.process = process
+
+ haystack = b"abcneedlexyz"
+ start = 0x1000
+
+ def fake_read_memory(address: int, size: int):
+ offset = address - start
+ return {"hex": haystack[offset : offset + size].hex()}
+
+ session.read_memory = MagicMock(side_effect=fake_read_memory)
+
+ data = LLDBSession.find_memory(session, "needle", start, len(haystack), chunk_size=5)
+
+ assert data["found"] is True
+ assert data["address"] == hex(start + 3)
+ assert session.read_memory.call_count >= 2
+
+ def test_find_memory_rejects_oversized_scan(self):
+ from cli_anything.lldb.core.session import LLDBSession, MEMORY_FIND_MAX_SCAN_SIZE
+
+ session = self._make_session()
+ process = MagicMock()
+ process.IsValid.return_value = True
+ session.process = process
+
+ with pytest.raises(ValueError) as exc:
+ LLDBSession.find_memory(session, "needle", 0x1000, MEMORY_FIND_MAX_SCAN_SIZE + 1)
+
+ assert "max supported scan size" in str(exc.value)
+
class TestCLISubprocess:
CLI_BASE = _resolve_cli("cli-anything-lldb")
diff --git a/lldb/agent-harness/cli_anything/lldb/utils/repl_skin.py b/lldb/agent-harness/cli_anything/lldb/utils/repl_skin.py
index c7312348a..bc1fb6d1d 100644
--- a/lldb/agent-harness/cli_anything/lldb/utils/repl_skin.py
+++ b/lldb/agent-harness/cli_anything/lldb/utils/repl_skin.py
@@ -7,7 +7,7 @@ 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
+ skin.print_banner() # auto-detects repo-root or packaged SKILL.md
prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)
skin.success("Project saved")
skin.error("File not found")
@@ -20,6 +20,7 @@ Usage:
import os
import sys
+from pathlib import Path
# โ”€โ”€ ANSI color codes (no external deps for core styling) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -57,6 +58,8 @@ _RED = "\033[38;5;196m"
_BLUE = "\033[38;5;75m"
_MAGENTA = "\033[38;5;176m"
+_SKILL_SOURCE_REPO = os.environ.get("CLI_ANYTHING_SKILL_REPO", "HKUDS/CLI-Anything")
+
# โ”€โ”€ Brand icon โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# The cli-anything icon: a small colored diamond/chevron mark
@@ -89,6 +92,17 @@ def _visible_len(text: str) -> int:
return len(_strip_ansi(text))
+def _display_home_path(path: str) -> str:
+ """Display a path relative to the home directory when possible."""
+ expanded = Path(path).expanduser().resolve()
+ home = Path.home().resolve()
+ try:
+ relative = expanded.relative_to(home)
+ return f"~/{relative.as_posix()}"
+ except ValueError:
+ return str(expanded)
+
+
class ReplSkin:
"""Unified REPL skin for cli-anything CLIs.
@@ -106,27 +120,44 @@ class ReplSkin:
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.
+ Auto-detected from the repo-root skills/ tree when present,
+ otherwise from the package's skills/ directory.
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)
+ software_aliases = {"iterm2_ctl": "iterm2"}
+ self.skill_slug = software_aliases.get(self.software, self.software).replace("_", "-")
+ self.skill_id = f"cli-anything-{self.skill_slug}"
+ self.skill_install_cmd = (
+ f"npx skills add {_SKILL_SOURCE_REPO} --skill {self.skill_id} -g -y"
+ )
+ global_skill_root = Path(
+ os.environ.get("CLI_ANYTHING_GLOBAL_SKILLS_DIR", str(Path.home() / ".agents" / "skills"))
+ ).expanduser()
+ self.global_skill_path = str(global_skill_root / self.skill_id / "SKILL.md")
+
+ # Prefer repo-root canonical skills/<skill-id>/SKILL.md when running
+ # inside the CLI-Anything monorepo. Fall back to the packaged
+ # cli_anything/<software>/skills/SKILL.md for installed harnesses.
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)
+ package_skill = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"
+ repo_skill = None
+ for parent in Path(__file__).resolve().parents:
+ candidate = parent / "skills" / self.skill_id / "SKILL.md"
+ if candidate.is_file():
+ repo_skill = candidate
+ break
+ if repo_skill and repo_skill.is_file():
+ skill_path = str(repo_skill)
+ elif package_skill.is_file():
+ skill_path = str(package_skill)
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")
@@ -156,7 +187,9 @@ class ReplSkin:
def print_banner(self):
"""Print the startup banner with branding."""
- inner = 54
+ import textwrap
+
+ inner = 72
def _box_line(content: str) -> str:
"""Wrap content in box drawing, padding to inner width."""
@@ -164,6 +197,24 @@ class ReplSkin:
vl = self._c(_DARK_GRAY, _V_LINE)
return f"{vl}{content}{' ' * max(0, pad)}{vl}"
+ def _meta_lines(label: str, value: str) -> list[str]:
+ """Wrap a metadata line for the banner box."""
+ icon = self._c(_MAGENTA, "โ—‡")
+ label_text = self._c(_DARK_GRAY, label)
+ prefix = f" {icon} {label_text} "
+ available = max(12, inner - _visible_len(prefix))
+ wrapped = textwrap.wrap(
+ value,
+ width=available,
+ break_long_words=True,
+ break_on_hyphens=False,
+ ) or [""]
+ lines = [f"{prefix}{self._c(_LIGHT_GRAY, wrapped[0])}"]
+ continuation_prefix = " " * _visible_len(prefix)
+ for chunk in wrapped[1:]:
+ lines.append(f"{continuation_prefix}{self._c(_LIGHT_GRAY, chunk)}")
+ return lines
+
top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")
bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")
@@ -178,19 +229,14 @@ class ReplSkin:
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}"
-
+ meta_lines: list[str] = []
+ meta_lines.extend(_meta_lines("Install:", self.skill_install_cmd))
+ meta_lines.extend(_meta_lines("Global skill:", _display_home_path(self.global_skill_path)))
print(top)
print(_box_line(title))
print(_box_line(ver))
- if skill_line:
- print(_box_line(skill_line))
+ for line in meta_lines:
+ print(_box_line(line))
print(_box_line(empty))
print(_box_line(tip))
print(bot)
diff --git a/lldb/agent-harness/cli_anything/lldb/utils/session_client.py b/lldb/agent-harness/cli_anything/lldb/utils/session_client.py
index 012e8b921..2b66c3c8f 100644
--- a/lldb/agent-harness/cli_anything/lldb/utils/session_client.py
+++ b/lldb/agent-harness/cli_anything/lldb/utils/session_client.py
@@ -4,18 +4,20 @@ Client-side helpers for the persistent LLDB session daemon.
from __future__ import annotations
-import base64
import hashlib
import json
import os
+import socket
+import struct
import subprocess
import sys
import tempfile
import time
-from multiprocessing.connection import Client
from pathlib import Path
from typing import Any
+MAX_MESSAGE_BYTES = 1024 * 1024
+
def resolve_session_file(explicit: str | None = None) -> Path:
if explicit:
@@ -31,14 +33,67 @@ def resolve_session_file(explicit: str | None = None) -> Path:
return (root / f"session-{digest}.json").resolve()
+def _validate_state_file(state_file: Path):
+ stat_result = state_file.stat()
+ if os.name != "nt":
+ if stat_result.st_uid != os.getuid():
+ raise RuntimeError(
+ f"Refusing to use session state file not owned by the current user: {state_file}"
+ )
+ if stat_result.st_mode & 0o077:
+ raise RuntimeError(f"Session state file permissions are too broad: {state_file}")
+
+
def _load_state_file(state_file: Path) -> dict[str, Any]:
+ _validate_state_file(state_file)
return json.loads(state_file.read_text(encoding="utf-8"))
-def _connect(state_file: Path):
+def _recv_exact(conn: socket.socket, size: int) -> bytes:
+ chunks = bytearray()
+ while len(chunks) < size:
+ chunk = conn.recv(size - len(chunks))
+ if not chunk:
+ raise ConnectionError("Unexpected EOF while reading response")
+ chunks.extend(chunk)
+ return bytes(chunks)
+
+
+def _recv_message(conn: socket.socket) -> dict[str, Any]:
+ header = _recv_exact(conn, 4)
+ message_size = struct.unpack("!I", header)[0]
+ if message_size <= 0 or message_size > MAX_MESSAGE_BYTES:
+ raise ValueError(f"Invalid message size: {message_size}")
+ payload = _recv_exact(conn, message_size)
+ message = json.loads(payload.decode("utf-8"))
+ if not isinstance(message, dict):
+ raise ValueError("Response payload must be a JSON object")
+ return message
+
+
+def _send_message(conn: socket.socket, payload: dict[str, Any]):
+ raw = json.dumps(payload).encode("utf-8")
+ if len(raw) > MAX_MESSAGE_BYTES:
+ raise ValueError("Request payload is too large")
+ conn.sendall(struct.pack("!I", len(raw)))
+ conn.sendall(raw)
+
+
+def _request(state_file: Path, method: str, *args, **kwargs):
state = _load_state_file(state_file)
- authkey = base64.b64decode(state["authkey"])
- return Client((state["host"], state["port"]), authkey=authkey)
+ token = state.get("token")
+ if not isinstance(token, str) or not token:
+ raise RuntimeError(f"Session state file is missing a valid token: {state_file}")
+
+ with socket.create_connection((state["host"], state["port"]), timeout=5.0) as conn:
+ payload = {
+ "token": token,
+ "method": method,
+ "args": list(args),
+ "kwargs": kwargs,
+ }
+ _send_message(conn, payload)
+ return _recv_message(conn)
def _spawn_server(state_file: Path):
@@ -64,9 +119,7 @@ def _spawn_server(state_file: Path):
def ensure_server(state_file: Path, timeout: float = 10.0):
if state_file.exists():
try:
- with _connect(state_file) as conn:
- conn.send({"method": "ping", "args": [], "kwargs": {}})
- response = conn.recv()
+ response = _request(state_file, "ping")
if response.get("ok"):
return
except Exception:
@@ -80,9 +133,7 @@ def ensure_server(state_file: Path, timeout: float = 10.0):
while time.time() < deadline:
if state_file.exists():
try:
- with _connect(state_file) as conn:
- conn.send({"method": "ping", "args": [], "kwargs": {}})
- response = conn.recv()
+ response = _request(state_file, "ping")
if response.get("ok"):
return
except Exception:
@@ -99,9 +150,7 @@ class RemoteLLDBSessionProxy:
def call(self, method: str, *args, **kwargs):
ensure_server(self._state_file)
- with _connect(self._state_file) as conn:
- conn.send({"method": method, "args": list(args), "kwargs": kwargs})
- response = conn.recv()
+ response = _request(self._state_file, method, *args, **kwargs)
if response.get("ok"):
return response.get("data")
raise RuntimeError(response.get("error") or f"Remote call failed: {method}")
diff --git a/lldb/agent-harness/cli_anything/lldb/utils/session_server.py b/lldb/agent-harness/cli_anything/lldb/utils/session_server.py
index 83467ba9a..d46b984ca 100644
--- a/lldb/agent-harness/cli_anything/lldb/utils/session_server.py
+++ b/lldb/agent-harness/cli_anything/lldb/utils/session_server.py
@@ -6,31 +6,57 @@ from __future__ import annotations
import argparse
import base64
+import hmac
import json
import os
import socket
+import struct
import sys
import time
-from multiprocessing.connection import Listener
from pathlib import Path
from typing import Any
from cli_anything.lldb.core.session import LLDBSession
+MAX_MESSAGE_BYTES = 1024 * 1024
-def _encode_authkey(authkey: bytes) -> str:
- return base64.b64encode(authkey).decode("ascii")
+def _encode_token(token: bytes) -> str:
+ return base64.b64encode(token).decode("ascii")
-def _write_state_file(state_file: Path, address: tuple[str, int], authkey: bytes):
- state_file.parent.mkdir(parents=True, exist_ok=True)
+
+def _prepare_state_dir(state_dir: Path):
+ state_dir.mkdir(parents=True, exist_ok=True)
+ if os.name != "nt":
+ try:
+ os.chmod(state_dir, 0o700)
+ except OSError:
+ pass
+
+
+def _write_state_file(state_file: Path, address: tuple[str, int], token: bytes):
+ _prepare_state_dir(state_file.parent)
payload = {
"host": address[0],
"port": address[1],
- "authkey": _encode_authkey(authkey),
+ "token": _encode_token(token),
"pid": os.getpid(),
}
- state_file.write_text(json.dumps(payload), encoding="utf-8")
+
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
+ flags |= getattr(os, "O_BINARY", 0)
+ if os.name != "nt":
+ flags |= getattr(os, "O_NOFOLLOW", 0)
+
+ fd = os.open(str(state_file), flags, 0o600)
+ with os.fdopen(fd, "w", encoding="utf-8") as state_fp:
+ json.dump(payload, state_fp)
+
+ if os.name != "nt":
+ try:
+ os.chmod(state_file, 0o600)
+ except OSError:
+ pass
def _remove_state_file(state_file: Path):
@@ -40,6 +66,48 @@ def _remove_state_file(state_file: Path):
pass
+def _recv_exact(conn: socket.socket, size: int) -> bytes:
+ chunks = bytearray()
+ while len(chunks) < size:
+ chunk = conn.recv(size - len(chunks))
+ if not chunk:
+ raise ConnectionError("Unexpected EOF while reading request")
+ chunks.extend(chunk)
+ return bytes(chunks)
+
+
+def _recv_message(conn: socket.socket) -> dict[str, Any]:
+ header = _recv_exact(conn, 4)
+ message_size = struct.unpack("!I", header)[0]
+ if message_size <= 0 or message_size > MAX_MESSAGE_BYTES:
+ raise ValueError(f"Invalid message size: {message_size}")
+ payload = _recv_exact(conn, message_size)
+ message = json.loads(payload.decode("utf-8"))
+ if not isinstance(message, dict):
+ raise ValueError("Request payload must be a JSON object")
+ return message
+
+
+def _send_message(conn: socket.socket, payload: dict[str, Any]):
+ raw = json.dumps(payload).encode("utf-8")
+ if len(raw) > MAX_MESSAGE_BYTES:
+ raise ValueError("Response payload is too large")
+ conn.sendall(struct.pack("!I", len(raw)))
+ conn.sendall(raw)
+
+
+def _validate_request(request: dict[str, Any]):
+ method = request.get("method")
+ args = request.get("args", [])
+ kwargs = request.get("kwargs", {})
+ if not isinstance(method, str) or not method:
+ raise ValueError("Request is missing a valid method name")
+ if not isinstance(args, list):
+ raise ValueError("Request args must be a list")
+ if not isinstance(kwargs, dict):
+ raise ValueError("Request kwargs must be an object")
+
+
class SessionServer:
"""Owns one persistent LLDBSession inside a lightweight RPC daemon."""
@@ -47,7 +115,8 @@ class SessionServer:
self._session: LLDBSession | None = None
def handle(self, request: dict[str, Any]) -> tuple[dict[str, Any], bool]:
- method = request.get("method")
+ _validate_request(request)
+ method = request["method"]
args = request.get("args", [])
kwargs = request.get("kwargs", {})
@@ -90,11 +159,13 @@ class SessionServer:
def serve(state_file: Path, idle_timeout: int = 300):
- authkey = os.urandom(32)
- listener = Listener(("127.0.0.1", 0), authkey=authkey)
- raw_socket = listener._listener._socket # type: ignore[attr-defined]
- raw_socket.settimeout(1.0)
- _write_state_file(state_file, listener.address, authkey)
+ token = os.urandom(32)
+ encoded_token = _encode_token(token)
+ server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ server_socket.bind(("127.0.0.1", 0))
+ server_socket.listen()
+ server_socket.settimeout(1.0)
+ _write_state_file(state_file, server_socket.getsockname(), token)
server = SessionServer()
last_activity = time.time()
@@ -102,22 +173,46 @@ def serve(state_file: Path, idle_timeout: int = 300):
try:
while True:
try:
- conn = listener.accept()
+ conn, _address = server_socket.accept()
except socket.timeout:
if time.time() - last_activity >= idle_timeout:
break
continue
last_activity = time.time()
+ should_stop = False
with conn:
- request = conn.recv()
- response, should_stop = server.handle(request)
- conn.send(response)
+ try:
+ request = _recv_message(conn)
+ request_token = request.get("token")
+ if not isinstance(request_token, str) or not hmac.compare_digest(
+ request_token, encoded_token
+ ):
+ response = {
+ "ok": False,
+ "error": "Unauthorized session client",
+ "type": "PermissionError",
+ }
+ else:
+ sanitized = {
+ "method": request.get("method"),
+ "args": request.get("args", []),
+ "kwargs": request.get("kwargs", {}),
+ }
+ response, should_stop = server.handle(sanitized)
+ except Exception as exc:
+ response = {
+ "ok": False,
+ "error": str(exc),
+ "type": exc.__class__.__name__,
+ }
+ _send_message(conn, response)
+
if should_stop:
break
finally:
server.close()
- listener.close()
+ server_socket.close()
_remove_state_file(state_file)