Metadata-Version: 2.4
Name: tianlong-toolkit
Version: 1.1.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
Dynamic: license-file

# Tianlong Toolkit (天龙工具箱)

> AI Agent 安全审计、健康监控、进化评估 — 全部免费开源。
> AI Agent security audit, health monitoring, evolution evaluation — 100% free & open source.

[![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-500%20passed-brightgreen)]()

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

---

## What is Tianlong Toolkit? / 天龙工具箱是什么？

A pure Python toolkit for **AI Agent security and operation**:

- **Security Audit** — 30 rules: prompt injection, unsafe exec, hardcoded keys, sandbox escape, path traversal, and more
- **Health Monitoring** — 8 system checks with HTML reports
- **Safety Guard** — 6 red-line rules preventing unsafe operations (deletion, data leak, legal compliance)
- **Evolution Engine** — Self-learning loop that analyzes failures and improves
- **Meta-Cognition** — SelfModel, MetaEVOLVE, DGM-H architecture for recursive self-improvement

AI Agent 安全审计、健康监控、运行时安全约束与自我进化的纯 Python 工具箱。

---

## Quick Start / 快速开始

### One-Command Audit / 一键审计

```bash
tianlong-audit -d . > audit.html
# Opens a beautiful dark-mode HTML report with health + security + evolution data
```

### Security Scan / 安全扫描

```bash
tianlong-uxu scan . --severity high
# Detects: hardcoded keys, exec/eval, shell injection, prompt injection, path traversal
```

### CI/CD Integration

```yaml
# .github/workflows/tianlong-audit.yml
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
```

### Agent Self-Learning / 自我进化

```bash
tianlong-agent start --detach      # Start evolution daemon
tianlong-agent status              # Check status
tianlong-agent run-once            # Run one evolution cycle
```

---

## Features / 功能

### 15 CLI Commands

| Command | Function / 功能 |
|---------|-----------------|
| `tianlong-audit` | Full audit (security + health + evolution) / 全量审计 |
| `tianlong-uxu scan` | Security audit (30 rules) / 安全审计 |
| `tianlong-monitor` | Health check / 健康检查 |
| `tianlong-safety` | Safety guard / 安全约束 |
| `tianlong-judge` | Evolution judge / 进化评估 |
| `tianlong-dashboard` | Global dashboard / 全局仪表盘 |
| `tianlong-agent` | Agent daemon / Agent 守护进程 |
| `agent-run` | Sub-agent runner / Agent 执行器 |

### 19 Python Modules

```
monitor safety judge evolution brain executor
reporter agents metacog onlinestate uxu dashboard
audit researchegine selfmodel metaevolve dgmh agent
```

### 30 Security Rules (UXU)

| Pillar | Count | Coverage |
|--------|-------|----------|
| Input Sanitization | 10 | Prompt injection, encoding bypass, path traversal |
| Sandbox Isolation | 10 | Exec escape, shell injection, network control, temp files |
| Privilege Minimization | 10 | Hardcoded keys, tool permissions, audit logging, token budget |

### 6 Safety Lines (R1-R6)

```
R1  No auto-delete                    R2  No data leak
R3  No destructive operations         R4  No self-rule modification
R5  No auto-authorization             R6  Legal compliance (GDPR/CCPA/中国法)
```

### 500 Tests · Pure Standard Library

Zero external dependencies. Works on Linux, macOS, Windows.

---

## Python API / 编程接口

### BrainCore — 决策引擎

```python
from tianlong.brain import BrainCore, Dispatcher, AgentRole

# 初始化（可选注入 Dispatcher）
disp = Dispatcher()
core = BrainCore(dispatcher=disp)

# 接收任务
task = core.receive(source="user", summary="调研AI安全")
print(f"路由: {task.target_module}, 优先级: P{task.priority}")

# 获取 Sub-Agent 派发参数
info = core.dispatch_to_agent(task)
if info and info["success"]:
    # 在 Hermes Agent 决策循环中: delegate_task(**info["params"])
    pass

# 状态快照
snap = core.snapshot()
print(f"队列: {snap.queue_length}, 空闲: {snap.is_idle}")
```

### Dispatcher — Sub-Agent 派发

```python
from tianlong.brain import Dispatcher, AgentRole

disp = Dispatcher()

# 构建参数
params = disp.build_params(
    role=AgentRole.RESEARCH,
    goal="调研OWASP Top 10 for LLM",
    context="关注提示注入攻击",
)
# params = {"goal": ..., "context": ..., "toolsets": ["terminal","web","search"], "max_iterations": 30}

# 记录结果（传入 delegate_task 的原始返回值）
result = disp.record_result(AgentRole.RESEARCH, "调研", raw_result, duration=15.3)
print(disp.format_result(result))   # ✅ [research] 调研 (15.3s)
print(result.brief())               # ✅ [research] 调研 (15.3s)
```

### Monitor — 健康检查

```python
from tianlong.monitor import run_all_checks
from pathlib import Path

report = run_all_checks(Path("."))
print(f"状态: {report.overall}")
print(f"通过: {report.summary['ok']}/{report.summary['total']}")
for c in report.checks:
    print(f"  {c.name}: {c.status} — {c.message}")
```

### UXU Scanner — 安全扫描

```python
from tianlong.uxu import Scanner

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

### SafetyGuard — 安全约束

```python
from tianlong.safety import SafetyGuard

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

### MetaCogTrigger — 退化检测

```python
from tianlong.metacog import MetaCogTrigger

trigger = MetaCogTrigger()
result = trigger.evaluate(
    success_rate_7d=0.92,
    success_rate_3d=0.85,
    days_since_last_improvement=2,
    repeat_error_count=1,
)
print(f"触发: {result.should_evolve} ({result.summary_line})")
```

### DGM-H — 元认知编排

```python
from tianlong.dgmh import DGOrchestrator

dgmh = DGOrchestrator()
dgmh.set_activation(user_authorized=True, judgestored=True)

# 检查激活状态
status = dgmh.check_activation()
print(f"Phase 2: {status.phase2_ready}")
print(f"Phase 3: {status.phase3_ready}")

# 运行 MetaEVOLVE 分析
report = dgmh.run_meta_evolve()
print(f"建议: {len(report.get('suggestions', []))} 条")
```

### Judge — 进化评估引擎

```python
from tianlong.judge import RuleBasedJudge, Proposal, JudgeHistory

judge = RuleBasedJudge()
result = judge.evaluate(Proposal(id="p1", summary="优化搜索流程"))
print(f"分数: {result.total_score}, 等级: {result.grade.value}")

# 历史记录
history = JudgeHistory(path="judge-history.json")
history.record(result.to_dict())
stats = history.statistics()
print(f"总评估: {stats['total']}, 通过率: {stats['pass_rate']:.0%}")
```

---

## Examples / 示例

```python
from tianlong.uxu import Scanner
scanner = Scanner()
report = scanner.scan(".")
print(f"Security grade: {report.grade} ({report.score}/100)")
for f in report.findings:
    print(f"  [{f.severity}] {f.rule_id}: {f.title}")
```

See [examples/](examples/) for complete demo projects.

---

## Documentation / 文档

- [Quick Start](QUICKSTART.md)
- [CLI Reference](CLI_REFERENCE.md)
- [Python API](README.md#python-api--编程接口) — 本文档中的 Python API 章节
- [Deployment Guide](DEPLOY.md)
- Examples: [Security Audit](examples/agent-security-audit/)
- [Sub-Agent Workflow](examples/subagent-workflow.py)

---

## License / 许可

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

---

## 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 30-rule audit specification (Chinese/English)
