Metadata-Version: 2.4
Name: tianlong-toolkit
Version: 1.7.0
Summary: 天龙工具箱 — Agent健康监控、安全约束与进化评估
Author: 天龙1号
License: MIT License
        
        Copyright (c) 2026 Tianlong Toolkit
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/
Keywords: agent,monitoring,safety,ai-agent
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: pro
Requires-Dist: tianlong-brain; extra == "pro"
Provides-Extra: enterprise
Requires-Dist: tianlong-brain; extra == "enterprise"
Requires-Dist: tianlong-dgmh; extra == "enterprise"
Requires-Dist: tianlong-metaevolve; extra == "enterprise"
Requires-Dist: tianlong-researchengine; extra == "enterprise"
Requires-Dist: tianlong-evolution; extra == "enterprise"
Requires-Dist: tianlong-memory; extra == "enterprise"
Provides-Extra: dependencies
Dynamic: license-file

# Tianlong Toolkit (天龙工具箱)

> **AI Agent 开发者的安全运维工具箱** — 安全审计、健康监控、进化评估、竞品情报。
>
> **For AI Agent developers**: Security audit, health monitoring, evolution evaluation, competitive intelligence.
>
> **Zero dependencies. Pure Python. MIT License.**

[![PyPI](https://img.shields.io/pypi/v/tianlong-toolkit)](https://pypi.org/project/tianlong-toolkit/)
[![Python](https://img.shields.io/badge/python-3.11%2B-blue)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
[![Tests](https://img.shields.io/badge/tests-838%20passed-brightgreen)]()
[![Code](https://img.shields.io/badge/source-20K%20lines-important)]()

```bash
pip install tianlong-toolkit
```

---

## Positioning / 产品定位

**天龙工具箱 = 安全检测工具，不是运行时防护工具。**

- 🔍 **检测** — 扫描代码找出 exec/subprocess/硬编码Key等风险
- ❌ **不防护** — 不会在运行时拦截这些操作（那是 SafetyGuard 做的事）
- ❌ **不替代** — 不是 LangChain/CrewAI 的替代品，而是一个辅助工具箱

UXU 的 SI（沙箱隔离）和 PM（权限最小化）规则是**关键词扫描规则**，不是运行时沙箱或权限拦截器。它们告诉你的代码里有没有 `exec()`、`subprocess.run(shell=True)`、硬编码的 API Key，但不阻止这些代码执行。

如果你的 Agent 需要运行时的安全防护，使用 `tianlong-safety`（6条红线）作为补充。

---

## Who Is This For? / 适用人群

| 角色 | 痛点 | 天龙工具箱能做什么 |
|------|------|-------------------|
| **AI Agent 开发者** | 不知道项目安不安全、要不要进化、代码有没有退步 | 一键安全审计 + 自检诊断 + 健康监控 |
| **Agent 框架项目维护者**（LangChain/CrewAI/AutoGPT） | CI/CD 缺乏安全门禁、无法量化代码质量 | CI/CD 集成 UXU 安全扫描 + 进化评估 |
| **Solo 开发者 / 小团队** | 没有专业安全/运维团队、预算有限 | 零依赖免费工具箱，一个 pip 装完 |
| **AI 创业公司 CTO** | Agent 跑起来不受控、没有管理视图 | 管理后台 Web 面板 + 6 条安全红线 |
| **开源 Agent 项目** | 贡献者代码可能引入安全风险 | 社区版免费审计，PR 自动检查安全 |
| **AI Safety 研究员** | 需要可扩展的安全规则引擎 | 32 条 UXU 规则 + AST 语义分析 |

---

## Features at a Glance / 功能速览

| 功能区 | 模块 | CLI 命令 | 适合谁 |
|--------|------|---------|--------|
| 🔒 **安全审计** | uxu (32规则) | `tianlong-uxu` | 所有 Agent 开发者 |
| 🩺 **健康监控** | monitor (8项检查) | `tianlong-monitor` | 生产环境运维 |
| 🛡️ **安全约束** | safety (6红线) | `tianlong-safety` | 自治 Agent 管控 |
| 📊 **进化评估** | judge + evolution | `tianlong-judge` | 自我改进型 Agent |
| 🖥️ **管理面板** | admin + dashboard | `tianlong-admin` | 日常管理 |
| 🕵️ **竞品情报** | compintel | `tianlong-compintel` | 产品竞争分析 |
| 🧠 **元认知** | metacog + dgmh + selfmodel + metaevolve | — | 高阶 Agent 治理 |
| 🔍 **自检诊断** | selfcheck | `tianlong-selfcheck` | 安装验证 |
| 🔗 **CI/CD 集成** | audit | `tianlong-audit` | DevOps 流程 |

---

## Quick Start / 快速开始

### 60 秒：一键全量审计
```bash
tianlong-audit -d . > audit.html
# 打开 audit.html — 漂亮的暗色模式报告，包含安全 + 健康 + 进化数据
```

### 安全扫描
```bash
tianlong-uxu scan . --severity high
# 检测: 硬编码密钥、exec/eval、Shell注入、Prompt注入、路径遍历
```

### 管理后台（浏览器操作）
```bash
tianlong-admin --serve --port 9901
# 打开 http://localhost:9901 — 全中文 Web 管理界面
```

### 自检诊断
```bash
tianlong-selfcheck           # 完整检查（版本/模块/CLI/文件完整性）
tianlong-selfcheck --quick   # 快速检查（仅关键模块）
```

### 自我进化守护进程
```bash
tianlong-agent start --detach   # 启动进化守护
tianlong-agent status           # 检查状态
tianlong-agent run-once         # 运行一次进化循环
```

---

## Use Cases / 应用场景

### 场景 1: Agent 项目 CI/CD 安全门禁
```yaml
# .github/workflows/tianlong-uxu.yml
# GitLab CI: .gitlab-ci.yml
# Local pre-commit: see CI/CD documentation
steps:
  - uses: actions/checkout@v4
  - uses: actions/setup-python@v5
    with: { python-version: '3.12' }
  - run: pip install tianlong-toolkit
  - run: tianlong-uxu scan . --severity high --json | jq '.score.grade'
  - run: test "$(tianlong-uxu scan . --json | python3 -c 'import sys,json; print(json.load(sys.stdin)["score"]["grade"])')" != "F"
```
🔥 **在 PR 合入前自动拦截高危漏洞**。

### 场景 2: Agent 进化质量管理
```bash
tianlong-judge history          # 查看所有进化提案评分与通过率
tianlong-dashboard              # 全局仪表盘（进化趋势 / UXU等级 / 健康状态）
```
🔥 **量化衡量你的 Agent 是否在持续改进**。

### 场景 3: 竞品动态追踪
```bash
tianlong-compintel sync                 # 真实采集 GitHub/PyPI/arXiv
tianlong-compintel sync --demo-mode     # 演示模式（模拟数据）
tianlong-compintel report --format markdown
```
🔥 **自动感知竞争对手的产品发布和论文**。

### 场景 4: 自省式 Agent（高阶）
```python
from tianlong.dgmh import DGOrchestrator
from tianlong.metacog import MetaCogTrigger
from tianlong.selfmodel import SelfModel

# 决策记忆
model = SelfModel()
model.record_decision("放弃功能X", reason="资源不足", outcome="正确")
print(model.top_decisions(5))  # 最近5条

# 退化检测
trigger = MetaCogTrigger()
r = trigger.evaluate(success_rate_7d=0.85, repeat_error_count=2)
if r.should_evolve:
    print(f"🍂 需要进化: {r.summary_line}")

# 元认知编排
dgmh = DGOrchestrator()
dgmh.set_activation(user_authorized=True, judgestored=True)
report = dgmh.run_meta_evolve()
```
🔥 **Agent 自己知道自己什么时候该进化**。

---

## 17 CLI Commands Reference

| Command / 命令 | Function / 功能 | Python API |
|---------------|-----------------|------------|
| `tianlong-audit` | 全量审计（安全+健康+进化） | — |
| `tianlong-uxu scan` | 安全审计 (32规则) | `from tianlong.uxu import Scanner` |
| `tianlong-monitor` | 健康检查 (8项) | `from tianlong.monitor import run_all_checks` |
| `tianlong-safety` | 安全约束 (6红线) | `from tianlong.safety import SafetyGuard` |
| `tianlong-judge` | 进化评估 | `from tianlong.judge import RuleBasedJudge` |
| `tianlong-dashboard` | 全局仪表盘 | `from tianlong.dashboard import build_dashboard` |
| `tianlong-admin` | 管理后台 | — (Web UI) |
| `tianlong-selfcheck` | 自检诊断 | `from tianlong.selfcheck import run_selfcheck` |
| `tianlong-agent` | Agent 守护进程 | `from tianlong.agent import start_daemon` |
| `agent-run` | Sub-Agent 执行器 | `from tianlong.agents import run_subagent` |
| `tianlong-brain` | BrainCore CLI | `from tianlong.brain import BrainCore` |
| `tianlong-brain-api` | BrainCore API网关 | — (HTTP API) |
| `tianlong-config` | 配置管理 | `from tianlong.config import ensure_config` |
| `tianlong-reporter` | 报告生成 | `from tianlong.reporter import Reporter` |
| `tianlong-desktop` | 桌面版启动器 | — (浏览器启动) |
| `tianlong-compintel` | 竞品情报 | `from tianlong.compintel import CompIntelTracker` |
| `tianlong-users` | 用户管理 | `from tianlong.users import UserManager` |

---

## 20 Python Modules

```
monitor  safety  judge  evolution  reporter  brain  executor
agents  metacog  onlinestate  uxu  dashboard  admin  selfcheck
researchengine  selfmodel  metaevolve  dgmh  sales  compintel  users
```

### 各模块一句话定位

| 模块 | 一句话 | 纯标准库 |
|------|--------|---------|
| `uxu` | 32 规则安全审计，AST 语义分析，OWASP Top 10 for LLM 覆盖 7/10 | ✅ |
| `monitor` | 8 项系统健康检查 + HTML 报告 | ✅ |
| `safety` | 6 条红线：不删除、不泄露、不破坏、不改规则、不自动授权、合规 | ✅ |
| `judge` | 进化提案评分（0-1）+ 等级（S/A/B/C/D/F） | ✅ |
| `evolution` | 完整进化闭环（分析→学习→验证→反射） | ✅ |
| `brain` | BrainCore 决策引擎 + 多租户 + Sub-Agent 派发 | ✅ |
| `admin` | Web 管理后台（零依赖 http.server） | ✅ |
| `dashboard` | HTML 仪表盘 | ✅ |
| `compintel` | 竞品追踪 + 真实采集（GitHub/PyPI/arXiv） | ✅ |
| `users` | 多用户管理 + Token 鉴权 + JSON 持久化 | ✅ |
| `dgmh` | DGM-H 元认知编排 + SafetyShield | ✅ |
| `metacog` | 退化检测触发引擎 | ✅ |
| `selfmodel` | 自我模型（决策记忆 + 能力画像） | ✅ |
| `metaevolve` | 元进化（ChangeRecord + 命中率分析 + 策略建议） | ✅ |
| `sales` | 销售 Pipeline（需 Enterprise 授权） | ✅ |
| `agent` + `agents` | Agent 守护进程 + Sub-Agent 协作框架 | ✅ |
| `researchengine` | 调研引擎（5 种类型 + 4 级搜索链） | ✅ |
| `executor` | 任务执行器 | ✅ |
| `onlinestate` | 在线状态管理 | ✅ |
| `selfcheck` | 一键自检（版本/模块/CLI/文件完整性） | ✅ |

**所有模块合计 20,800 行 Python，零外部依赖。**

---

## Security: UXU 32 Rules + AST

| Pillar | Rules | What It Detects |
|--------|-------|-----------------|
| **Input Sanitization (IS)** | 12 | Prompt injection, encoding bypass, path traversal, f-string injection |
| **Sandbox Isolation (SI)** | 10 | exec/eval escape, shell injection, network control, temp file abuse |
| **Privilege Minimization (PM)** | 10 | Hardcoded keys, tool permissions, audit logging, token budget |

覆盖 **OWASP Top 10 for LLM Applications** 7/10 类别。

```python
from tianlong.uxu import Scanner

scanner = Scanner(min_severity="medium")
report = scanner.scan("src/")
print(f"Grade: {report.score.grade}  |  Findings: {report.total_findings}")
for f in report.findings[:5]:
    print(f"  [{f.severity}] {f.rule_id}: {f.matched_text[:60]}")
```

---

## Architecture / 架构

```
用户指令 / Cron / 心跳
        ↓
  ┌─ BrainCore（决策路由 + 多租户）
  │      ↓
  │  SafetyGuard（安全检查 — 6 条红线）
  │      ↓
  ├─ Monitor → Health Report
  ├─ UXU Scanner → Security Report
  ├─ Judge → Evolution Score
  ├─ MetaCog → Degradation Detection
  ├─ DGM-H → Meta-Cognition Orchestrator
  ├─ CompIntel → Competitive Intelligence
  └─ Admin → Web Dashboard
```

---

## Python API Examples

### Security + Health + Evolution in 3 Lines
```python
from tianlong.uxu import Scanner
from tianlong.monitor import run_all_checks
from tianlong.judge import RuleBasedJudge, Proposal

scan = Scanner().scan(".")
health = run_all_checks(".")
judge = RuleBasedJudge().evaluate(Proposal(id="p1", summary="My improvement"))

print(f"Security: {scan.score.grade}  Health: {health.overall}  Evolution: {judge.grade.value}")
```

### Safety Guard
```python
from tianlong.safety import SafetyGuard

guard = SafetyGuard()
allowed, reason = guard.check("write", target="sensitive_file.txt")
if not allowed:
    print(f"🚫 Blocked: {reason}")
```

### BrainCore Sub-Agent Dispatch
```python
from tianlong.brain import BrainCore, Dispatcher, AgentRole

core = BrainCore()
cmd = core.execute_subagent(
    role=AgentRole.RESEARCH,
    goal="调研 AI Agent 安全框架",
)
# → delegate_task(**cmd["params"])
```

### Full List of Python APIs
| Module | Class / Function | What It Does |
|--------|-----------------|--------------|
| `tianlong.uxu` | `Scanner` | 32-rule security audit |
| `tianlong.monitor` | `run_all_checks()` | 8 health checks |
| `tianlong.safety` | `SafetyGuard` | 6 red-line guard |
| `tianlong.judge` | `RuleBasedJudge`, `JudgeHistory` | Evolution evaluation |
| `tianlong.evolution` | `SelfLearning` | Learning loop |
| `tianlong.brain` | `BrainCore`, `Dispatcher`, `AgentRole` | Decision engine |
| `tianlong.agent` | `start_daemon()` | Evolution daemon |
| `tianlong.agents` | `run_subagent()` | Sub-agent runner |
| `tianlong.compintel` | `CompIntelTracker`, `IntelReport` | Competitive intel |
| `tianlong.users` | `UserManager` | Multi-user auth |
| `tianlong.metacog` | `MetaCogTrigger` | Degradation detection |
| `tianlong.dgmh` | `DGOrchestrator` | Meta-cognition |
| `tianlong.selfmodel` | `SelfModel` | Self-modeling |
| `tianlong.metaevolve` | `MetaEVOLVE` | Meta-evolution |
| `tianlong.researchengine` | `ResearchEngine` | Research automation |
| `tianlong.executor` | `Executor` | Task execution |
| `tianlong.onlinestate` | `OnlineState` | State management |
| `tianlong.selfcheck` | `run_selfcheck()` | Self-diagnosis |
| `tianlong.dashboard` | `build_dashboard()` | Dashboard HTML |
| `tianlong.reporter` | `Reporter` | Report generation |

---

## CI/CD Integration / 持续集成

### GitHub Actions
```yaml
# .github/workflows/tianlong-audit.yml
name: Tianlong Security Audit
on: [push, pull_request]
jobs:
  audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: { python-version: '3.12' }
      - run: pip install tianlong-toolkit
      - run: tianlong-audit -d . > audit.html
      - uses: actions/upload-artifact@v4
        with: { name: audit-report, path: audit.html }
```

### GitLab CI
```yaml
# .gitlab-ci.yml
tianlong-audit:
  image: python:3.12-slim
  script:
    - pip install tianlong-toolkit
    - tianlong-uxu scan . --json > uxu-report.json
    - tianlong-selfcheck --json > selfcheck.json
  artifacts:
    paths: [uxu-report.json, selfcheck.json]
```

### Pre-commit Hook (local)
```bash
# .git/hooks/pre-commit 或 .pre-commit-config.yaml
pip install tianlong-toolkit
tianlong-uxu scan . --severity high --json
if [ $? -ne 0 ]; then echo "❌ 安全扫描未通过"; exit 1; fi
```

---

## Project Stats

| Metric | Value |
|--------|-------|
| Version | v1.7.0 |
| Source Lines | 20,801 |
| Python Modules | 20 |
| CLI Commands | 17 |
| Tests | 838 |
| UXU Rules | 32 (IS:12, SI:10, PM:10) |
| Safety Rules | 6 (R1-R6) |
| Dependencies | **Zero** (pure stdlib) |
| License | MIT |
| Python | 3.11+ (tested on 3.12) |
| Platforms | Linux, macOS, Windows |
| i18n | 登录页双语(中/EN), 管理后台中文, README 英中混合 |

---

## Documentation / 文档

- [Quick Start Guide](QUICKSTART.md)
- [CLI Reference](CLI_REFERENCE.md) — 全部 17 条命令用法
- [Python API Reference](docs/api.md) — 20 模块 API
- [Deployment Guide](DEPLOY.md)
- [CI/CD Guide](CI_CD.md) — GitHub Actions, GitLab CI, CircleCI, Pre-commit
- [Changelog](CHANGELOG.md)
- [Contributing Guide](CONTRIBUTING.md)
- [Commercial License](COMMERCIAL_LICENSE.md)

---

## License / 许可

**MIT** — 100% free and open source. No API keys, no license files, no registration.
完全免费开源，无需任何授权或 API Key。

Enterprise features available via [tianlong-admin](https://github.com/) (commercial license required).

---

## Related / 关联项目

- [Hermes Agent](https://github.com/NousResearch/hermes-agent) — The runtime that inspired the evolution architecture
- [UXU Specification](https://github.com/tianlong-toolkit/uxu-spec) — The 32-rule audit specification

---

*Made with 🐉 for the AI Agent community.*
