# boss-skills API · Integration Cookbook

> v1 (2026-05-28) · ADR-004 落地 · 5 个 sync endpoint
>
> 任何 HTTP client 都能调 — 这里给 4 种典型 runtime 的接入示例: curl / Python / Hermes-like / OpenClaw-like。

## 1. 端点速查

| Method | Path | Tag | 用途 |
|---|---|---|---|
| GET | `/v1/healthz` | meta | Liveness probe |
| GET | `/v1/version` | meta | skill name / version / git commit |
| GET | `/v1/panels` | config | 列 panels/*.yaml + 评委 |
| GET | `/v1/anchors` | config | 列 anchors/*/ + perspective skill 状态 |
| POST | `/v1/attribution/check` | action | 触发 attribution_check.py run, 同步返回 summary |

OpenAPI 3.0 spec: [`openapi.json`](openapi.json) (~ 7 KB · FastAPI auto-generated)

Interactive docs (server 跑起来后): `http://localhost:8421/docs` (Swagger UI) · `/redoc` (ReDoc)

---

## 2. 起 server (本地 / Docker / 云)

### 本地直跑 (开发)

```bash
pip install -r requirements.txt
python3 -m uvicorn scripts.boss_server:app --host 127.0.0.1 --port 8421 --reload
```

### Docker (推荐生产用法)

```bash
docker build -t boss-vault:v0.3.0 .

docker run -d --name boss-api \
  -p 8421:8421 \
  -e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY \
  -v $(pwd)/anchors:/app/anchors:ro \
  -v $(pwd)/panels:/app/panels:ro \
  -v $(pwd)/cases:/app/cases \
  boss-vault:v0.3.0

curl http://localhost:8421/v1/healthz
```

### 云部署 (D2)

systemd + nginx 模板: [`templates/boss-hermes.service.example`](../../templates/boss-hermes.service.example) + [`templates/nginx-boss-hermes.conf.example`](../../templates/nginx-boss-hermes.conf.example) · 用 `__VAULT_ROOT__` / `__USER__` / `__DOMAIN__` 占位符替换即可。

---

## 3. 客户端示例 · 4 种 runtime 接入

### 3.1 · curl (shell, 最简)

```bash
BOSS_API="http://localhost:8421"

# health + version
curl -s $BOSS_API/v1/healthz | jq .
curl -s $BOSS_API/v1/version | jq .

# 列 panels (含 anchor_slug + judges)
curl -s $BOSS_API/v1/panels | jq '.panels[0]'

# 列 anchors (含 perspective skill 状态)
curl -s $BOSS_API/v1/anchors | jq '.'

# 触发 attribution (dry_run)
curl -s -X POST $BOSS_API/v1/attribution/check \
     -H "Content-Type: application/json" \
     -d '{"dry_run": true}' | jq .

# 触发 attribution 真跑 (单 case)
curl -s -X POST $BOSS_API/v1/attribution/check \
     -H "Content-Type: application/json" \
     -d '{"dry_run": false, "case_id": "_demo-acmeco-strategy"}' | jq .
```

### 3.2 · Python (requests / httpx)

```python
import httpx

BOSS_API = "http://localhost:8421"

with httpx.Client(base_url=BOSS_API, timeout=30) as client:
    # 1. health check
    r = client.get("/v1/healthz")
    r.raise_for_status()
    print(r.json())

    # 2. version
    v = client.get("/v1/version").json()
    print(f"skill: {v['skill']} {v['skill_version']} · git: {v['git_commit']}")

    # 3. list panels + judges
    panels = client.get("/v1/panels").json()
    for p in panels["panels"]:
        print(f"  panel: {p['name']} · anchor={p['anchor_slug']} · {len(p['judges'])} judges")

    # 4. list anchors
    anchors = client.get("/v1/anchors").json()
    default = anchors["default_anchor_slug"]
    print(f"default anchor: {default}")
    for a in anchors["anchors"]:
        print(f"  - {a['slug']} (perspective={a['perspective_skill_exists']})")

    # 5. run attribution
    r = client.post("/v1/attribution/check", json={"dry_run": True})
    summary = r.json()
    print(f"attribution: checked={summary['total_checked']} · by_status={summary['by_status']}")
```

### 3.3 · Hermes-like runtime (Python daemon · webhook + cron)

如果你在写一个 always-on agent runtime (类似 boss-vault 设计中的 Hermes), 想接 boss-skills 作为下游:

```python
"""hermes_to_boss.py · 你的 Hermes runtime 调 boss-skills 的示例"""
from typing import Any
import httpx
import asyncio

BOSS_API = "http://boss-api.internal:8421"   # 内网域名 / k8s service

class BossSkillsClient:
    def __init__(self, base_url: str = BOSS_API, timeout: float = 30.0):
        self.client = httpx.AsyncClient(base_url=base_url, timeout=timeout)

    async def health(self) -> bool:
        r = await self.client.get("/v1/healthz")
        return r.status_code == 200 and r.json().get("status") == "ok"

    async def panels(self) -> list[dict[str, Any]]:
        r = await self.client.get("/v1/panels")
        r.raise_for_status()
        return r.json()["panels"]

    async def anchors(self) -> list[dict[str, Any]]:
        r = await self.client.get("/v1/anchors")
        r.raise_for_status()
        return r.json()["anchors"]

    async def run_attribution(self, case_id: str | None = None, dry_run: bool = False):
        r = await self.client.post(
            "/v1/attribution/check",
            json={"case_id": case_id, "dry_run": dry_run},
        )
        r.raise_for_status()
        return r.json()


# 你的 Hermes 调度 loop · 每天 09:00 调一次 attribution
async def hermes_attribution_job():
    async with BossSkillsClient() as boss:
        if not await boss.health():
            raise RuntimeError("boss-skills API down")
        result = await boss.run_attribution(dry_run=False)
        print(f"attribution run: {result['by_status']}")
        # 把 result 写回你的 storage / push 到飞书 / etc.


# 你的 Hermes 接飞书 webhook 时, 先 query boss-skills 看 panel 配置
async def hermes_lark_webhook_handler(event: dict):
    async with BossSkillsClient() as boss:
        panels = await boss.panels()
        # ... 你的业务逻辑: 根据 event topic 选 panel, 触发 judgement (v2 API)
```

### 3.4 · OpenClaw-like runtime (任意 LLM Agent framework)

如果你的 LLM Agent framework (OpenClaw / LangChain / AutoGen / 自写) 想把 boss-skills 注册为可调工具:

**LangChain 风格**:

```python
from langchain.tools import Tool
import httpx

BOSS_API = "http://localhost:8421"

def boss_list_panels(_input: str = "") -> str:
    r = httpx.get(f"{BOSS_API}/v1/panels")
    r.raise_for_status()
    return r.text

def boss_list_anchors(_input: str = "") -> str:
    r = httpx.get(f"{BOSS_API}/v1/anchors")
    r.raise_for_status()
    return r.text

tools = [
    Tool(name="boss_panels", func=boss_list_panels,
         description="List available judgement panels from boss-skills. Returns JSON."),
    Tool(name="boss_anchors", func=boss_list_anchors,
         description="List available anchor profiles from boss-skills. Returns JSON."),
]
# tools 可以注入 OpenClaw / LangChain / AutoGen / etc.
```

**MCP-style (未来 v0.4 直接做 MCP server)**:

```yaml
# 用户的 ~/.config/openclaw/agents.yaml (示意)
agents:
  - name: boss-judgement
    type: http
    base_url: https://boss-api.example.com
    auth:
      type: bearer
      token: ${BOSS_API_TOKEN}
    tools:
      - name: list_panels
        endpoint: GET /v1/panels
      - name: list_anchors
        endpoint: GET /v1/anchors
      - name: run_attribution
        endpoint: POST /v1/attribution/check
```

---

## 4. 错误处理

| HTTP code | 含义 | 客户端动作 |
|---|---|---|
| 200 | OK | 解析 response.json() |
| 422 | Pydantic validation error | 看 response.json().detail, 修请求 schema |
| 500 | Internal error | 重试 1 次; 若仍 fail, log + 报警 |
| 504 | attribution_check timeout > 30s | 重试; 若 case 很多, 用 case_id 限定单 case |

---

## 5. 限速 / Auth (v1 未实现)

v1 sync API 默认**无 auth**, 适合内网 / 本地 / 信任的 LAN 环境。

**生产 / 公网部署强烈建议加** (推迟到 v0.4):

- Reverse proxy auth (nginx + basic auth / API key header)
- Rate limit (nginx `limit_req` / FastAPI middleware)
- TLS (certbot + nginx 见 `templates/nginx-boss-hermes.conf.example`)
- IP allowlist (nginx `allow` / `deny`)

---

## 6. v2 路线 (推迟)

v1 sync API 不接完整 Phase 0-5 流水线 (~ 45 min runtime)。v2 计划:

- `POST /v2/judgement` · 异步触发, 返回 `job_id`
- `GET /v2/judgement/{job_id}` · 查状态 (pending / running / done / failed)
- `GET /v2/judgement/{job_id}/result` · 拿 report.md + reviews
- Webhook callback (你的 runtime 提供 URL, boss-skills 完成后 POST 通知)
- in-memory job queue → Redis-backed queue (生产化)

v2 触发信号 (来自 ADR-004):
- v1 实际使用 ≥ 30 天, 用户反馈接口稳定
- 外部 runtime 明确表达 "想从 HTTP 触发完整 judgement" 需求

---

## 7. 相关文档

- [ADR-004 · boss-skills as a product](../adr/ADR-004-boss-skills-as-product.md) (positioning)
- [`docs/deployment.md`](../deployment.md) (三形态部署)
- [`docs/adr/ADR-003`](../adr/ADR-003-deployment-as-optional.md) (deployment as optional)
- [`scripts/boss_server.py`](../../scripts/boss_server.py) (server 实现)
- [`Dockerfile`](../../Dockerfile) (容器化)
- [`openapi.json`](openapi.json) (OpenAPI 3.0 spec, auto-generated)

---

*v1 cookbook · 2026-05-28 · ADR-004 落地 · 见 [`docs/showcase/2026-05-28-boss-skills-api.html`](../showcase/2026-05-28-boss-skills-api.html) 互动信息图*
