Skip to content

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

Python

Fix LLDB session persistence and coverage

aimidid4d5b10bf499
diff --git a/.gitignore b/.gitignore
index a7d961b11..523a68a8b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -94,6 +94,7 @@
!/openscreen/
!/n8n/
!/obsidian/
+!/lldb/
# Step 5: Inside each software dir, ignore everything (including dotfiles)
/gimp/*
@@ -174,6 +175,8 @@
/n8n/.*
/obsidian/*
/obsidian/.*
+/lldb/*
+/lldb/.*
# Step 6: ...except agent-harness/
!/gimp/agent-harness/
@@ -221,6 +224,7 @@
!/obsidian/agent-harness/
!/safari/
!/safari/agent-harness/
+!/lldb/agent-harness/
# Step 7: Ignore build artifacts within allowed dirs
**/__pycache__/
diff --git a/README.md b/README.md
index 48b9b0dea..d5524b1d8 100644
--- a/README.md
+++ b/README.md
@@ -14,8 +14,8 @@ CLI-Anything: Bridging the Gap Between AI Agents and the World's Software</stron
<p align="center">
<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-16_Apps-green?style=for-the-badge" alt="Demos"></a>
- <a href="#-test-results"><img src="https://img.shields.io/badge/Tests-2%2C130_Passing-brightgreen?style=for-the-badge" alt="Tests"></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%2C159_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>
@@ -567,6 +567,7 @@ The catalog auto-updates whenever `registry.json` changes — new community CLIs
| **🌐 Network & Infrastructure** | Manage network services, DNS, ad-blocking, and infrastructure through structured CLI commands | AdGuardHome |
| **🧪 Testing & Mocking** | Control HTTP mock servers, manage test stubs, record and replay API traffic for integration testing | **[WireMock](https://wiremock.org)** |
| **🔬 Graphics & GPU Debugging** | Analyze GPU frame captures, inspect pipeline state, export shaders, and diff rendering state | RenderDoc |
+| **🐞 Native Debugging** | Inspect processes, threads, frames, breakpoints, expressions, and memory through debugger-native APIs | **[LLDB](https://lldb.llvm.org)** |
| **🎬 Video & Subtitles** | Transcribe speech, translate subtitles, burn styled captions into video — full captioning pipeline | VideoCaptioner |
| **🔍 AI-Native Search** | Neural and deep web search with structured content retrieval through embedding-based APIs | [Exa](https://exa.ai) |
| **✨ AI Content Generation** | Generate professional deliverables (slides, docs, diagrams, websites, research reports) through AI-powered cloud APIs | [AnyGen](https://www.anygen.io), Gamma, Beautiful.ai, Tome |
@@ -586,7 +587,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" | 1,839+ tests with real software validation. Battle-tested across 16 major applications |
+| ⚡ "Prototype vs Production gap" | 2,159+ tests with real software validation. Battle-tested across 31 major applications |
---
@@ -745,7 +746,7 @@ An agent uses the VideoCaptioner CLI to automatically generate and overlay style
CLI-Anything works on any software with a codebase — no domain restrictions or architectural limitations.
### 🏭 Professional-Grade Testing
-Tested across 16 diverse, complex applications spanning creative, productivity, communication, diagramming, AI image generation, AI content generation, network ad blocking, and local LLM inference domains previously inaccessible to AI agents.
+Tested across 31 diverse, complex applications spanning creative, productivity, communication, debugging, diagramming, AI image generation, AI content generation, network ad blocking, and local LLM inference domains previously inaccessible to AI agents.
### 🎨 Diverse Domain Coverage
From creative workflows (image editing, 3D modeling, vector graphics) to production tools (audio, office, live streaming, video editing).
@@ -874,6 +875,13 @@ Each application received complete, production-ready CLI interfaces — not demo
<td align="center">✅ 138</td>
</tr>
<tr>
+<td align="center"><strong>🐞 <a href="lldb/agent-harness/">LLDB</a></strong></td>
+<td>Native Debugging</td>
+<td><code>cli-anything-lldb</code></td>
+<td>LLDB Python API</td>
+<td align="center">✅ 21</td>
+</tr>
+<tr>
<td align="center"><strong>⛓️ ETH2 QuickStart</strong></td>
<td>DevOps / Ethereum</td>
<td><code>cli-anything-eth2-quickstart</code></td>
@@ -973,11 +981,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,130</strong></td>
+<td align="center"><strong>✅ 2,159</strong></td>
</tr>
</table>
-> **100% pass rate** across all 2,130 tests — 1,551 unit tests + 560 end-to-end tests + 19 Node.js tests.
+> **100% pass rate** across all 2,159 tests — 1,570 unit tests + 570 end-to-end tests + 19 Node.js tests.
---
@@ -1005,6 +1013,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)
eth2-quickstart 18 passed ✅ (18 unit + 3 e2e skipped)
mermaid 10 passed ✅ (5 unit + 5 e2e)
anygen 50 passed ✅ (40 unit + 10 e2e)
@@ -1018,7 +1027,7 @@ cloudcompare 88 passed ✅ (49 unit + 39 e2e)
openscreen 101 passed ✅ (78 unit + 23 e2e)
cloudanalyzer 14 passed ✅ (7 unit + 7 e2e)
──────────────────────────────────────────────────────────────────────────────
-TOTAL 2,120 passed ✅ 100% pass rate
+TOTAL 2,159 passed ✅ 100% pass rate
```
---
@@ -1092,10 +1101,11 @@ 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)
├── 🎬 videocaptioner/agent-harness/ # VideoCaptioner CLI (26 tests)
├── 🎬 openscreen/agent-harness/ # Openscreen CLI — screen recording editor (101 tests)
├── ☁️ cloudcompare/agent-harness/ # CloudCompare CLI (88 tests)
-├── 🔍 exa/agent-harness/ # Exa CLI (40 tests)
+├── 🔍 exa/agent-harness/ # Exa CLI (40 tests)
└── ⛅ cloudanalyzer/agent-harness/ # CloudAnalyzer CLI (14 tests)
```
@@ -1197,7 +1207,7 @@ HARNESS.md is our definitive SOP for making any software agent-accessible via au
It encodes proven patterns and methodologies refined through automated generation processes.
-The playbook distills key insights from successfully building all 16 diverse, production-ready harnesses.
+The playbook distills key insights from successfully building all 31 diverse, production-ready harnesses.
### Critical Lessons
@@ -1322,7 +1332,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 | 16 professional software demos | 1,839 passing tests</sub>
+<sub>A methodology for the age of AI agents | 31 professional software demos | 2,159 passing tests</sub>
<br>
diff --git a/README_CN.md b/README_CN.md
index a8ca794ee..9b584d335 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -9,8 +9,8 @@ CLI-Anything:连接 AI Agent 与全世界软件的桥梁</strong><br>
<p align="center">
<a href="#-快速上手"><img src="https://img.shields.io/badge/快速上手-5_分钟-blue?style=for-the-badge" alt="Quick Start"></a>
- <a href="#-实测展示"><img src="https://img.shields.io/badge/Demo-11_款软件-green?style=for-the-badge" alt="Demos"></a>
- <a href="#-测试结果"><img src="https://img.shields.io/badge/测试-1%2C508_通过-brightgreen?style=for-the-badge" alt="Tests"></a>
+ <a href="#-实测展示"><img src="https://img.shields.io/badge/Demo-15_款软件-green?style=for-the-badge" alt="Demos"></a>
+ <a href="#-测试结果"><img src="https://img.shields.io/badge/测试-1%2C649_通过-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>
@@ -352,6 +352,7 @@ cli-anything-gimp
| **🤖 AI/ML 平台** | 用结构化命令驱动模型训练、推理流水线和超参搜索 | Stable Diffusion WebUI、ComfyUI、InvokeAI、Text-generation-webui、Open WebUI、Fooocus、Kohya_ss、AnythingLLM、SillyTavern |
| **📊 数据与分析** | 以编程方式完成数据处理、可视化和统计分析工作流 | JupyterLab、Apache Superset、Metabase、Redash、DBeaver、KNIME、Orange、OpenSearch Dashboards、Lightdash |
| **💻 开发工具** | 通过 CLI 串联代码编辑、构建、测试与部署流程 | Jenkins、Gitea、Hoppscotch、Portainer、pgAdmin、SonarQube、ArgoCD、OpenLens、Insomnia、Beekeeper Studio |
+| **🐞 调试与分析** | 通过原生调试器 API 检查进程、线程、栈帧、断点、表达式和内存 | LLDB |
| **🎨 创意与媒体** | 以编程方式控制内容创作、编辑和渲染工作流 | Blender、GIMP、OBS Studio、Audacity、Krita、Kdenlive、Shotcut、Inkscape、Darktable、LMMS、Ardour |
| **📐 图表与可视化** | 以编程方式创建和操作流程图、架构图、ER 图等各类图表 | Draw.io (diagrams.net)、Mermaid、PlantUML、Excalidraw、yEd |
| **🔬 科学计算** | 自动化科研工作流、仿真模拟和复杂计算 | ImageJ、FreeCAD、QGIS、ParaView、Gephi、LibreCAD、Stellarium、KiCad、JASP、Jamovi |
@@ -374,7 +375,7 @@ AI Agent 推理能力很强,但操控真实专业软件的能力很弱。现
| 💸 "GUI 自动化三天两头崩" | 告别截图、点击和 RPA 的脆弱性,纯命令行操控,结构化接口 |
| 📊 "Agent 需要结构化数据" | 内置 JSON 输出供 Agent 直接消费,同时保留可读格式方便调试 |
| 🔧 "定制集成太贵了" | 一个插件就能为任意代码库自动生成 CLI,经过验证的 7 阶段流水线 |
-| ⚡ "原型和生产之间差十万八千里" | 1,508+ 测试用例,全部在真实软件上验证通过,覆盖 11 款主流应用 |
+| ⚡ "原型和生产之间差十万八千里" | 1,649+ 测试用例,全部在真实软件上验证通过,覆盖 15 款主流应用 |
---
@@ -471,7 +472,7 @@ CLI-Anything 适用于任何有代码库的软件 —— 不限领域,不限
### 🏭 专业级测试
-在 11 款复杂应用上进行了实测,涵盖创意、生产力、通信、图表和 AI 内容生成领域 —— 这些软件此前对 AI Agent 来说几乎不可触及。
+在 15 款复杂应用上进行了实测,涵盖创意、生产力、通信、调试、图表和 AI 内容生成领域 —— 这些软件此前对 AI Agent 来说几乎不可触及。
### 🎨 覆盖多元领域
@@ -574,6 +575,13 @@ CLI-Anything 适用于任何有代码库的软件 —— 不限领域,不限
<td align="center">✅ 138</td>
</tr>
<tr>
+<td align="center"><strong>🐞 <a href="lldb/agent-harness/">LLDB</a></strong></td>
+<td>原生调试</td>
+<td><code>cli-anything-lldb</code></td>
+<td>LLDB Python API</td>
+<td align="center">✅ 21</td>
+</tr>
+<tr>
<td align="center"><strong>✨ AnyGen</strong></td>
<td>AI 内容生成</td>
<td><code>cli-anything-anygen</code></td>
@@ -589,11 +597,11 @@ CLI-Anything 适用于任何有代码库的软件 —— 不限领域,不限
</tr>
<tr>
<td align="center" colspan="4"><strong>合计</strong></td>
-<td align="center"><strong>✅ 1,527</strong></td>
+<td align="center"><strong>✅ 1,649</strong></td>
</tr>
</table>
-> 全部 1,628 项测试 **100% 通过** —— 1,151 项单元测试 + 458 项端到端测试 + 19 项 Node.js 测试。
+> 全部 1,649 项测试 **100% 通过** —— 1,169 项单元测试 + 461 项端到端测试 + 19 项 Node.js 测试。
---
@@ -621,10 +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)
anygen 50 passed ✅ (40 unit + 10 e2e)
sketch 19 passed ✅ (19 jest, Node.js)
──────────────────────────────────────────────────────────────────────────────
-TOTAL 1,628 passed ✅ 100% pass rate
+TOTAL 1,649 passed ✅ 100% pass rate
```
---
@@ -690,6 +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 项测试)
├── ✨ anygen/agent-harness/ # AnyGen CLI(50 项测试)
└── 🎨 sketch/agent-harness/ # Sketch CLI(19 项测试,Node.js)
```
@@ -793,7 +803,7 @@ HARNESS.md 是我们通过自动化 CLI 生成,使任意软件具备 Agent 可
它记录了在自动化生成过程中经验证并沉淀出的模式与方法论。
-这本手册提炼了成功构建全部 11 套生产级 CLI 的关键经验。
+这本手册提炼了成功构建全部 15 套生产级 CLI 的关键经验。
### 核心经验
@@ -927,7 +937,7 @@ MIT License — 可自由使用、修改和分发。
**CLI-Anything** — *一行命令,让任何软件成为 Agent 的原生工具。*
-<sub>为 AI Agent 时代而生 | 11 款专业软件实测 | 1,508 项测试全部通过</sub>
+<sub>为 AI Agent 时代而生 | 15 款专业软件实测 | 1,649 项测试全部通过</sub>
<br>
diff --git a/lldb/agent-harness/cli_anything/lldb/README.md b/lldb/agent-harness/cli_anything/lldb/README.md
index 3cdb56c22..54d814dde 100644
--- a/lldb/agent-harness/cli_anything/lldb/README.md
+++ b/lldb/agent-harness/cli_anything/lldb/README.md
@@ -53,10 +53,18 @@ cli-anything-lldb --json frame locals
# Evaluate expression
cli-anything-lldb --json expr "argc"
+# Close the persistent session when you are done
+cli-anything-lldb --json session close
+
# Start REPL (default mode)
cli-anything-lldb
```
+Non-REPL commands share a persistent LLDB session automatically, so commands
+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.
+
## Command Groups
- `target`: `create`, `info`
@@ -68,6 +76,7 @@ cli-anything-lldb
- `expr`
- `memory`: `read`, `find`
- `core`: `load`
+- `session`: `info`, `close`
- `repl`
## JSON Output
@@ -87,5 +96,5 @@ pytest cli_anything/lldb/tests/test_full_e2e.py -v
```
E2E tests require:
-- `LLDB_TEST_EXE` pointing to a runnable test executable
+- a working C compiler (`clang`, `gcc`, or `cc`) so the tests can build a small debug helper
- optional `LLDB_TEST_CORE` for core-load scenario
diff --git a/lldb/agent-harness/cli_anything/lldb/core/session.py b/lldb/agent-harness/cli_anything/lldb/core/session.py
index 2493c9b0a..7918c6f90 100644
--- a/lldb/agent-harness/cli_anything/lldb/core/session.py
+++ b/lldb/agent-harness/cli_anything/lldb/core/session.py
@@ -35,6 +35,7 @@ class LLDBSession:
self.debugger.SetAsync(False)
self.target = None
self.process = None
+ self._process_origin: str | None = None
def target_create(self, exe_path: str, arch: Optional[str] = None) -> Dict[str, Any]:
arch = arch or self._lldb.LLDB_ARCH_DEFAULT
@@ -66,6 +67,7 @@ class LLDBSession:
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()
def attach_name(self, name: str, wait_for: bool = False) -> Dict[str, Any]:
@@ -78,6 +80,7 @@ class LLDBSession:
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()
def launch(
@@ -90,6 +93,7 @@ class LLDBSession:
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")
+ self._process_origin = "launched"
return self._process_info()
def detach(self) -> Dict[str, Any]:
@@ -97,6 +101,8 @@ class LLDBSession:
error = self.process.Detach()
if not error.Success():
raise RuntimeError(f"Detach failed: {error}")
+ self.process = None
+ self._process_origin = None
return {"status": "detached"}
def breakpoint_set(
@@ -275,14 +281,38 @@ class LLDBSession:
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()
def destroy(self):
if self.process and self.process.IsValid():
- self.process.Kill()
+ try:
+ if self._process_origin == "attached":
+ self.process.Detach()
+ elif self._process_origin == "launched":
+ state = self.process.GetState()
+ if state not in (
+ self._lldb.eStateDetached,
+ self._lldb.eStateExited,
+ ):
+ self.process.Kill()
+ except Exception:
+ pass
+ finally:
+ self.process = None
+ self._process_origin = None
self._lldb.SBDebugger.Destroy(self.debugger)
self._lldb.SBDebugger.Terminate()
+ def session_status(self) -> Dict[str, Any]:
+ has_target = bool(self.target and self.target.IsValid())
+ has_process = bool(self.process and self.process.IsValid())
+ return {
+ "has_target": has_target,
+ "has_process": has_process,
+ "process_origin": self._process_origin if has_process else None,
+ }
+
def _require_target(self):
if self.target is None or not self.target.IsValid():
raise RuntimeError("No target. Create target first.")
diff --git a/lldb/agent-harness/cli_anything/lldb/lldb_cli.py b/lldb/agent-harness/cli_anything/lldb/lldb_cli.py
index 3eac7ee57..b5fed5c11 100644
--- a/lldb/agent-harness/cli_anything/lldb/lldb_cli.py
+++ b/lldb/agent-harness/cli_anything/lldb/lldb_cli.py
@@ -13,14 +13,27 @@ from typing import Optional
import click
_session = None # type: ignore
-_repl_mode = False
+_session_file = None
-def _close_session():
+def _set_session_file(path: str | None):
+ global _session, _session_file
+ if _session_file != path:
+ _session = None
+ _session_file = path
+
+
+def _shutdown_session():
global _session
if _session is not None:
- _session.destroy()
- _session = None
+ shutdown = getattr(_session, "shutdown", None)
+ try:
+ if callable(shutdown):
+ shutdown()
+ else:
+ _session.destroy()
+ finally:
+ _session = None
def _parse_int(value: str) -> int:
@@ -30,22 +43,35 @@ def _parse_int(value: str) -> int:
def _get_session():
global _session
if _session is None:
- from cli_anything.lldb.core.session import LLDBSession
+ from cli_anything.lldb.utils.session_client import RemoteLLDBSessionProxy, resolve_session_file
- _session = LLDBSession()
+ _session = RemoteLLDBSessionProxy(resolve_session_file(_session_file))
return _session
+def _session_status(session):
+ status_fn = getattr(session, "session_status", None)
+ if callable(status_fn):
+ status = status_fn()
+ if isinstance(status, dict):
+ return status
+ return {
+ "has_target": getattr(session, "target", None) is not None,
+ "has_process": getattr(session, "process", None) is not None,
+ "process_origin": None,
+ }
+
+
def _require_target():
s = _get_session()
- if s.target is None:
+ if not _session_status(s).get("has_target"):
raise click.ClickException("No target. Run: target create --exe <path>")
return s
def _require_process():
s = _require_target()
- if s.process is None:
+ if not _session_status(s).get("has_process"):
raise click.ClickException("No process. Run: process launch/attach or core load")
return s
@@ -83,22 +109,34 @@ def _handle_exc(ctx: click.Context, exc: Exception):
@click.group(invoke_without_command=True)
@click.option("--json", "json_mode", is_flag=True, help="Output in JSON format.")
@click.option("--debug", is_flag=True, help="Show debug tracebacks on errors.")
+ "--session-file",
+ type=click.Path(dir_okay=False),
+ default=None,
+ help="Optional persistent session state file path.",
+)
@click.version_option(package_name="cli-anything-lldb")
@click.pass_context
-def cli(ctx, json_mode, debug):
+def cli(ctx, json_mode, debug, session_file):
"""LLDB CLI - stateful debugger harness with REPL and subcommands."""
+ from cli_anything.lldb.utils.session_client import resolve_session_file
+
ctx.ensure_object(dict)
ctx.obj["json_mode"] = json_mode
ctx.obj["debug"] = debug
+ ctx.obj["session_file"] = str(resolve_session_file(session_file))
+ ctx.obj.setdefault("close_session_on_exit", False)
+ _set_session_file(ctx.obj["session_file"])
if ctx.invoked_subcommand is None:
+ ctx.obj["close_session_on_exit"] = True
ctx.invoke(repl)
@cli.result_callback()
@click.pass_context
def _cleanup(ctx, _result, **_kwargs):
- if not _repl_mode:
- _close_session()
+ if ctx.obj.get("close_session_on_exit"):
+ _shutdown_session()
# ===========================================================================
@@ -525,6 +563,39 @@ def core_load(ctx, core_path: str):
_handle_exc(ctx, exc)
+# ===========================================================================
+# session
+# ===========================================================================
+
+
+def session_group():
+ """Persistent session lifecycle helpers."""
+
+
+@session_group.command("info")
+def session_info(ctx):
+ """Show the current persistent session status."""
+ try:
+ data = _session_status(_get_session())
+ data["session_file"] = ctx.obj.get("session_file")
+ _output(ctx, data)
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
+@session_group.command("close")
+def session_close(ctx):
+ """Close the persistent session and clean up debugger state."""
+ try:
+ _shutdown_session()
+ _output(ctx, {"status": "closed", "session_file": ctx.obj.get("session_file")})
+ except Exception as exc:
+ _handle_exc(ctx, exc)
+
+
# ===========================================================================
# repl
# ===========================================================================
@@ -536,9 +607,6 @@ 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()
@@ -553,6 +621,7 @@ def repl(ctx):
"expr": "<expression>",
"memory": "read|find",
"core": "load",
+ "session": "info|close",
"help": "Show this help",
"quit": "Exit REPL",
}
@@ -560,7 +629,13 @@ def repl(ctx):
try:
while True:
try:
- context = "attached" if _session is not None else ""
+ context = ""
+ if _session is not None:
+ status = _session_status(_session)
+ if status.get("has_process"):
+ context = status.get("process_origin") or "active"
+ elif status.get("has_target"):
+ context = "target"
line = skin.get_input(pt_session, project_name=context, modified=False)
if not line:
continue
@@ -571,12 +646,16 @@ def repl(ctx):
skin.help(repl_commands)
continue
args = shlex.split(line, posix=os.name != "nt")
+ if ctx.obj.get("session_file"):
+ args = ["--session-file", ctx.obj["session_file"], *args]
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)
+ command_obj = dict(ctx.obj)
+ command_obj["close_session_on_exit"] = False
+ cli.main(args, standalone_mode=False, obj=command_obj)
except SystemExit:
pass
except click.exceptions.UsageError as exc:
@@ -590,8 +669,7 @@ def repl(ctx):
skin.print_goodbye()
break
finally:
- _repl_mode = False
- _close_session()
+ _shutdown_session()
def main():
diff --git a/lldb/agent-harness/cli_anything/lldb/tests/TEST.md b/lldb/agent-harness/cli_anything/lldb/tests/TEST.md
index 7affdce51..c4772aa70 100644
--- a/lldb/agent-harness/cli_anything/lldb/tests/TEST.md
+++ b/lldb/agent-harness/cli_anything/lldb/tests/TEST.md
@@ -2,8 +2,8 @@
## Test Inventory Plan
-- `test_core.py`: 24 unit tests planned
-- `test_full_e2e.py`: 9 E2E tests planned
+- `test_core.py`: persistent session + lifecycle unit tests
+- `test_full_e2e.py`: persistent workflow / attach cleanup / optional core-load E2E tests
## Unit Test Plan
@@ -28,25 +28,26 @@
- Validate breakpoint set/list/delete/enable operations
- Validate step/continue/backtrace/locals/evaluate return schemas
- Validate thread/frame select logic
-- Planned tests: 9
+- Validate cleanup semantics for attached vs launched inferiors
### `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
+- Validate persistent session command surface (`session info` / `session close`)
## E2E Test Plan
### Prerequisites
- LLDB installed and available in PATH
-- A debuggable executable path via `LLDB_TEST_EXE`
+- A C compiler (`clang`, `gcc`, or `cc`) so the tests can build a small debug helper
+- optional `LLDB_TEST_CORE` for the core-load negative-path check
### 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`)
+- Create target in one command, read target info in a later command via the same persisted session
+- Set breakpoint -> launch -> inspect threads/backtrace/locals -> evaluate expression -> read/find memory -> step -> continue
+- Attach to a live process, then close the LLDB session without killing the attached process
+- Load core dump negative path (optional; controlled by `LLDB_TEST_CORE`)
### Output validation
- All command responses parse as valid JSON in `--json` mode
@@ -55,31 +56,33 @@
## Realistic Workflow Scenarios
-### Workflow name: `hello_debug_session`
-- Simulates: attaching CLI agent to a simple debug loop executable
+### Workflow name: `persistent_probe_session`
+- Simulates: a CLI agent running multi-step debugger commands as separate invocations
- Operations chained:
1. `target create`
- 2. `process launch`
+ 2. `target info`
3. `breakpoint set`
- 4. `process continue`
+ 4. `process launch`
5. `thread backtrace`
6. `frame locals`
7. `expr`
+ 8. `memory read`
+ 9. `memory find`
+ 10. `step over`
- Verified:
- - execution state changes
+ - session persistence across non-REPL commands
+ - breakpoint hit and stopped-state inspection
- backtrace frame list shape
- expression result object shape
-### Workflow name: `inspect_memory_window`
-- Simulates: low-level memory inspection around known buffer addresses
+### Workflow name: `attach_cleanup_session`
+- Simulates: attaching to a live process and then shutting down the LLDB session
- Operations chained:
1. `target create`
- 2. `process launch`
- 3. `memory read`
- 4. `memory find`
+ 2. `process attach --pid <pid>`
+ 3. `session close`
- Verified:
- - deterministic hex payload length
- - successful needle lookup format
+ - attached process remains alive after the debugger session closes
## Test Results
@@ -87,13 +90,15 @@
```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
+python -m pytest cli_anything/lldb/tests/test_full_e2e.py -v -s
+python -m pytest cli_anything/lldb/tests -q
```
### Result summary
-- `test_core.py`: 15 passed
+- `test_core.py`: 18 passed
- `test_full_e2e.py`: 3 passed, 1 skipped
+- combined: 21 passed, 1 skipped
- Skip reason: `LLDB_TEST_CORE` was not provided, so the optional core-dump scenario was not exercised
### Notes
@@ -101,3 +106,5 @@ LLDB_TEST_EXE=C:\Users\aimidi\AppData\Local\Programs\Python\Python311\python.exe
- 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
+- Added a persistent background LLDB session so non-REPL commands can share debugger state
+- 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 a9af01e59..20db279f9 100644
--- a/lldb/agent-harness/cli_anything/lldb/tests/test_core.py
+++ b/lldb/agent-harness/cli_anything/lldb/tests/test_core.py
@@ -120,7 +120,7 @@ class TestCLIHelp:
from cli_anything.lldb.lldb_cli import cli
runner = CliRunner()
- for group in ("target", "process", "breakpoint", "thread", "frame", "step", "memory", "core"):
+ for group in ("target", "process", "breakpoint", "thread", "frame", "step", "memory", "core", "session"):
result = runner.invoke(cli, [group, "--help"])
assert result.exit_code == 0, f"{group} help failed"
@@ -177,6 +177,68 @@ class TestBackend:
assert "LLDB not found" in str(exc.value)
+class TestSessionLifecycle:
+ def _make_session(self):
+ from cli_anything.lldb.core.session import LLDBSession
+
+ session = object.__new__(LLDBSession)
+ session._lldb = MagicMock()
+ session._lldb.eStateDetached = 9
+ session._lldb.eStateExited = 10
+ session.debugger = MagicMock()
+ session.target = None
+ session.process = None
+ session._process_origin = None
+ return session
+
+ def test_destroy_detaches_attached_process(self):
+ from cli_anything.lldb.core.session import LLDBSession
+
+ session = self._make_session()
+ process = MagicMock()
+ process.IsValid.return_value = True
+ session.process = process
+ session._process_origin = "attached"
+
+ LLDBSession.destroy(session)
+
+ process.Detach.assert_called_once()
+ process.Kill.assert_not_called()
+ session._lldb.SBDebugger.Destroy.assert_called_once_with(session.debugger)
+ session._lldb.SBDebugger.Terminate.assert_called_once()
+
+ def test_destroy_kills_launched_process(self):
+ from cli_anything.lldb.core.session import LLDBSession
+
+ session = self._make_session()
+ process = MagicMock()
+ process.IsValid.return_value = True
+ process.GetState.return_value = 5
+ session.process = process
+ session._process_origin = "launched"
+
+ LLDBSession.destroy(session)
+
+ process.Kill.assert_called_once()
+ process.Detach.assert_not_called()
+
+ def test_session_status_reports_target_and_process(self):
+ from cli_anything.lldb.core.session import LLDBSession
+
+ session = self._make_session()
+ session.target = MagicMock()
+ session.target.IsValid.return_value = True
+ session.process = MagicMock()
+ session.process.IsValid.return_value = True
+ session._process_origin = "attached"
+
+ status = LLDBSession.session_status(session)
+
+ assert status["has_target"] is True
+ assert status["has_process"] is True
+ assert status["process_origin"] == "attached"
+
+
class TestCLISubprocess:
CLI_BASE = _resolve_cli("cli-anything-lldb")
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
index c9fe4072e..aa72e5dcd 100644
--- a/lldb/agent-harness/cli_anything/lldb/tests/test_full_e2e.py
+++ b/lldb/agent-harness/cli_anything/lldb/tests/test_full_e2e.py
@@ -1,13 +1,16 @@
"""
-End-to-end tests for LLDB CLI harness.
+End-to-end tests for the LLDB CLI harness.
-Requires LLDB installed and a test executable path in LLDB_TEST_EXE.
+These tests exercise the persistent session behavior added for non-REPL
+workflows, plus core debugger operations on a tiny compiled helper program.
"""
from __future__ import annotations
import json
import os
+import re
+import shutil
import subprocess
import sys
from pathlib import Path
@@ -15,12 +18,47 @@ 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
+HELPER_SOURCE = r"""
+#include <stdio.h>
+#include <string.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static void pause_ms(int ms) { Sleep(ms); }
+#else
+#include <unistd.h>
+static void pause_ms(int ms) { usleep((useconds_t)ms * 1000); }
+#endif
+
+char GLOBAL_BUFFER[] = "agent-native-lldb";
+
+int probe(int a, int b) {
+ int total = a + b;
+ pause_ms(50);
+ return GLOBAL_BUFFER[0] + total;
+}
+
+int run_attach_mode(void) {
+ pause_ms(4000);
+ return 0;
+}
+
+int main(int argc, char** argv) {
+ if (argc > 1 && strcmp(argv[1], "sleep") == 0) {
+ return run_attach_mode();
+ }
+
+ int value = probe(2, 40);
+ printf("value=%d\n", value);
+ fflush(stdout);
+ pause_ms(50);
+ return 0;
+}
+"""
+
try:
import lldb # noqa: F401
@@ -29,83 +67,175 @@ 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"]
+def _find_compiler() -> str | None:
+ for name in ("clang", "gcc", "cc"):
+ path = shutil.which(name)
+ if path:
+ return path
+ return None
+
+
[email protected](scope="session")
+def lldb_test_exe(tmp_path_factory) -> str:
+ compiler = _find_compiler()
+ if not compiler:
+ pytest.skip("No C compiler found for LLDB E2E helper build")
+
+ build_dir = tmp_path_factory.mktemp("lldb-e2e")
+ src = build_dir / "lldb_helper.c"
+ src.write_text(HELPER_SOURCE, encoding="utf-8")
+
+ exe_name = "lldb_helper.exe" if os.name == "nt" else "lldb_helper"
+ exe_path = build_dir / exe_name
+
+ cmd = [compiler, "-g", "-O0", str(src), "-o", str(exe_path)]
+ result = subprocess.run(cmd, capture_output=True, text=True)
+ if result.returncode != 0:
+ pytest.skip(f"Failed to build LLDB E2E helper: {result.stderr.strip()}")
+
+ return str(exe_path)
+
+
+def session_file(tmp_path) -> Path:
+ return tmp_path / "lldb-session.json"
+
+
+def _run_cli(*args, session_file: Path, input_text: str | None = None, timeout: int = 90) -> dict:
+ cmd = [
+ sys.executable,
+ "-m",
+ "cli_anything.lldb.lldb_cli",
+ "--json",
+ "--session-file",
+ str(session_file),
+ ]
cmd.extend(args)
result = subprocess.run(
cmd,
+ input=input_text,
capture_output=True,
text=True,
- timeout=90,
+ timeout=timeout,
cwd=HARNESS_ROOT,
)
if result.returncode != 0:
- raise RuntimeError(f"CLI failed: {result.stderr}\n{result.stdout}")
+ raise RuntimeError(f"CLI failed ({' '.join(args)}): {result.stderr}\n{result.stdout}")
return json.loads(result.stdout)
+def _close_session(session_file: Path):
+ cmd = [
+ sys.executable,
+ "-m",
+ "cli_anything.lldb.lldb_cli",
+ "--json",
+ "--session-file",
+ str(session_file),
+ "session",
+ "close",
+ ]
+ subprocess.run(cmd, capture_output=True, text=True, timeout=30, cwd=HARNESS_ROOT)
+
+
+def _extract_address(payload: dict) -> str:
+ for key in ("value", "summary"):
+ value = payload.get(key)
+ if isinstance(value, str):
+ match = re.search(r"0x[0-9a-fA-F]+", value)
+ if match:
+ return match.group(0)
+ raise AssertionError(f"Could not extract address from payload: {payload}")
+
+
@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
+ def test_persistent_target_info(self, lldb_test_exe: str, session_file: Path):
+ try:
+ create = _run_cli("target", "create", "--exe", lldb_test_exe, session_file=session_file)
+ info = _run_cli("target", "info", session_file=session_file)
+ finally:
+ _close_session(session_file)
+
+ assert create["executable"] == lldb_test_exe
+ assert info["executable"]
+ assert info["num_breakpoints"] == 0
+
+ def test_breakpoint_step_expr_and_memory_workflow(self, lldb_test_exe: str, session_file: Path):
+ try:
+ _run_cli("target", "create", "--exe", lldb_test_exe, session_file=session_file)
+ bp = _run_cli("breakpoint", "set", "--function", "probe", session_file=session_file)
+ launched = _run_cli("process", "launch", session_file=session_file)
+ threads = _run_cli("thread", "list", session_file=session_file)
+ backtrace = _run_cli("thread", "backtrace", session_file=session_file)
+ locals_payload = _run_cli("frame", "locals", session_file=session_file)
+ expr_payload = _run_cli("expr", "a + b", session_file=session_file)
+ address_payload = _run_cli("expr", "(char*)&GLOBAL_BUFFER[0]", session_file=session_file)
+ addr = _extract_address(address_payload)
+ memory = _run_cli("memory", "read", "--address", addr, "--size", "32", session_file=session_file)
+ found = _run_cli(
+ "memory",
+ "find",
+ "agent-native-lldb",
+ "--start",
+ addr,
+ "--size",
+ "32",
+ session_file=session_file,
+ )
+ stepped = _run_cli("step", "over", session_file=session_file)
+ _run_cli("breakpoint", "delete", "--id", str(bp["id"]), session_file=session_file)
+ finished = _run_cli("process", "continue", session_file=session_file)
+ finally:
+ _close_session(session_file)
+
+ assert launched["state"] == "stopped"
+ assert bp["locations"] >= 1
+ assert threads["threads"]
+ assert backtrace["frames"]
+ local_names = {item["name"] for item in locals_payload["variables"]}
+ assert {"a", "b"} <= local_names
+ assert expr_payload["error"] is None
+ assert expr_payload["value"] in {"42", "0x2a"}
+ assert len(memory["hex"]) >= 32
+ assert found["found"] is True
+ assert stepped["address"].startswith("0x")
+ assert finished["state"] in {"exited", "stopped"}
+
+ def test_attach_cleanup_does_not_kill_process(self, lldb_test_exe: str, session_file: Path):
+ proc = subprocess.Popen([lldb_test_exe, "sleep"], cwd=Path(lldb_test_exe).parent)
+ try:
+ _run_cli("target", "create", "--exe", lldb_test_exe, session_file=session_file)
+ attached = _run_cli("process", "attach", "--pid", str(proc.pid), session_file=session_file)
+ assert attached["pid"] == proc.pid
+
+ _close_session(session_file)
+
+ assert proc.poll() is None
+ finally:
+ if proc.poll() is None:
+ proc.terminate()
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait(timeout=5)
@skip_no_lldb
-@skip_no_exe
@skip_no_core
class TestCoreE2E:
- def test_core_load_requires_target(self):
+ def test_core_load_requires_target(self, session_file: Path):
cmd = [
sys.executable,
"-m",
"cli_anything.lldb.lldb_cli",
"--json",
+ "--session-file",
+ str(session_file),
"core",
"load",
"--path",
diff --git a/lldb/agent-harness/cli_anything/lldb/utils/session_client.py b/lldb/agent-harness/cli_anything/lldb/utils/session_client.py
new file mode 100644
index 000000000..012e8b921
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/utils/session_client.py
@@ -0,0 +1,122 @@
+"""
+Client-side helpers for the persistent LLDB session daemon.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import time
+from multiprocessing.connection import Client
+from pathlib import Path
+from typing import Any
+
+
+def resolve_session_file(explicit: str | None = None) -> Path:
+ if explicit:
+ return Path(explicit).expanduser().resolve()
+
+ env_override = os.environ.get("CLI_ANYTHING_LLDB_SESSION_FILE")
+ if env_override:
+ return Path(env_override).expanduser().resolve()
+
+ scope = os.environ.get("CLI_ANYTHING_LLDB_SESSION_SCOPE") or os.getcwd()
+ digest = hashlib.sha256(os.path.abspath(scope).encode("utf-8")).hexdigest()[:12]
+ root = Path(tempfile.gettempdir()) / "cli-anything-lldb"
+ return (root / f"session-{digest}.json").resolve()
+
+
+def _load_state_file(state_file: Path) -> dict[str, Any]:
+ return json.loads(state_file.read_text(encoding="utf-8"))
+
+
+def _connect(state_file: Path):
+ state = _load_state_file(state_file)
+ authkey = base64.b64decode(state["authkey"])
+ return Client((state["host"], state["port"]), authkey=authkey)
+
+
+def _spawn_server(state_file: Path):
+ cmd = [
+ sys.executable,
+ "-m",
+ "cli_anything.lldb.utils.session_server",
+ "--state-file",
+ str(state_file),
+ ]
+ popen_kwargs: dict[str, Any] = {
+ "stdin": subprocess.DEVNULL,
+ "stdout": subprocess.DEVNULL,
+ "stderr": subprocess.DEVNULL,
+ }
+ if os.name == "nt":
+ popen_kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
+ else:
+ popen_kwargs["start_new_session"] = True
+ subprocess.Popen(cmd, **popen_kwargs)
+
+
+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()
+ if response.get("ok"):
+ return
+ except Exception:
+ try:
+ state_file.unlink()
+ except FileNotFoundError:
+ pass
+
+ _spawn_server(state_file)
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if state_file.exists():
+ try:
+ with _connect(state_file) as conn:
+ conn.send({"method": "ping", "args": [], "kwargs": {}})
+ response = conn.recv()
+ if response.get("ok"):
+ return
+ except Exception:
+ pass
+ time.sleep(0.1)
+ raise RuntimeError("Timed out starting the LLDB session daemon")
+
+
+class RemoteLLDBSessionProxy:
+ """Thin RPC proxy that mirrors LLDBSession methods."""
+
+ def __init__(self, state_file: Path):
+ self._state_file = state_file
+
+ 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()
+ if response.get("ok"):
+ return response.get("data")
+ raise RuntimeError(response.get("error") or f"Remote call failed: {method}")
+
+ def session_status(self):
+ return self.call("session_status")
+
+ def shutdown(self):
+ try:
+ return self.call("shutdown")
+ finally:
+ try:
+ self._state_file.unlink()
+ except FileNotFoundError:
+ pass
+
+ def __getattr__(self, name: str):
+ return lambda *args, **kwargs: self.call(name, *args, **kwargs)
diff --git a/lldb/agent-harness/cli_anything/lldb/utils/session_server.py b/lldb/agent-harness/cli_anything/lldb/utils/session_server.py
new file mode 100644
index 000000000..83467ba9a
--- /dev/null
+++ b/lldb/agent-harness/cli_anything/lldb/utils/session_server.py
@@ -0,0 +1,138 @@
+"""
+Background LLDB session server for persistent non-REPL workflows.
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import json
+import os
+import socket
+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
+
+
+def _encode_authkey(authkey: bytes) -> str:
+ return base64.b64encode(authkey).decode("ascii")
+
+
+def _write_state_file(state_file: Path, address: tuple[str, int], authkey: bytes):
+ state_file.parent.mkdir(parents=True, exist_ok=True)
+ payload = {
+ "host": address[0],
+ "port": address[1],
+ "authkey": _encode_authkey(authkey),
+ "pid": os.getpid(),
+ }
+ state_file.write_text(json.dumps(payload), encoding="utf-8")
+
+
+def _remove_state_file(state_file: Path):
+ try:
+ state_file.unlink()
+ except FileNotFoundError:
+ pass
+
+
+class SessionServer:
+ """Owns one persistent LLDBSession inside a lightweight RPC daemon."""
+
+ def __init__(self):
+ self._session: LLDBSession | None = None
+
+ def handle(self, request: dict[str, Any]) -> tuple[dict[str, Any], bool]:
+ method = request.get("method")
+ args = request.get("args", [])
+ kwargs = request.get("kwargs", {})
+
+ if method == "ping":
+ return {"ok": True, "data": {"status": "ok"}}, False
+
+ if method == "session_status":
+ status = self._session.session_status() if self._session is not None else {
+ "has_target": False,
+ "has_process": False,
+ "process_origin": None,
+ }
+ return {"ok": True, "data": status}, False
+
+ if method == "shutdown":
+ self.close()
+ return {"ok": True, "data": {"status": "closed"}}, True
+
+ if method == "target_create" and self._session is not None:
+ self.close()
+
+ try:
+ if self._session is None:
+ self._session = LLDBSession()
+
+ handler = getattr(self._session, method)
+ data = handler(*args, **kwargs)
+ return {"ok": True, "data": data}, False
+ except Exception as exc:
+ return {
+ "ok": False,
+ "error": str(exc),
+ "type": exc.__class__.__name__,
+ }, False
+
+ def close(self):
+ if self._session is not None:
+ self._session.destroy()
+ self._session = None
+
+
+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)
+
+ server = SessionServer()
+ last_activity = time.time()
+
+ try:
+ while True:
+ try:
+ conn = listener.accept()
+ except socket.timeout:
+ if time.time() - last_activity >= idle_timeout:
+ break
+ continue
+
+ last_activity = time.time()
+ with conn:
+ request = conn.recv()
+ response, should_stop = server.handle(request)
+ conn.send(response)
+ if should_stop:
+ break
+ finally:
+ server.close()
+ listener.close()
+ _remove_state_file(state_file)
+
+
+def main(argv: list[str] | None = None):
+ parser = argparse.ArgumentParser(description="Internal LLDB session daemon")
+ parser.add_argument("--state-file", required=True, help="Session state file path")
+ parser.add_argument(
+ "--idle-timeout",
+ type=int,
+ default=int(os.environ.get("CLI_ANYTHING_LLDB_IDLE_TIMEOUT", "300")),
+ help="Seconds of inactivity before daemon exits",
+ )
+ args = parser.parse_args(argv)
+ serve(Path(args.state_file), idle_timeout=args.idle_timeout)
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])