# PRD: OPC Claude Access Gateway — 订阅制替代 API 计费方案

> **版本：** v1.0
> **日期：** 2026-04-24
> **负责人：** 小研（需求研究员）
> **优先级：** HIGH — 直接影响 OPC 多 Agent 系统运营成本

---

## 1. Problem & User

**核心问题：** OPC 现有 8+ 个 Agent（小策、小研、小码、小质、小文、小数、小推等），每个 Agent 通过 Anthropic API 按 token 计费调用 Claude 模型。随着 Agent 数量和使用频率增加，月度 API 费用线性增长，难以控制和预测。

**目标用户：** OPC 技术负责人（Bo）及多 Agent 系统运维团队

**痛点排序（来自真实用户反馈）：**
- P1 — API 成本随 Agent 数量线性增长，8 个 Agent 同时运行时月费难控
- P2 — Claude Code 订阅（$100-200/月）在高频 Agent 场景下仍会触及速率限制
- P3 — 各 Agent 独立配置 API key，无集中管理和成本归因
- P4 — Claude Code SDK 在 OpenClaw 多 Agent 架构中集成方案未验证

---

## 2. Target Outcome & KPIs

**目标：** 在不降低 Agent 能力的前提下，将 OPC 月度 Claude 调用成本降低 50% 以上，同时建立可观测的成本控制体系。

**KPIs：**
- 月 Claude 费用：从当前 API 按量计费 → 降至固定订阅 $100-200/月
- Agent 并发调用成功率：≥ 95%（不因限速导致任务失败）
- 成本归因：每个 Agent 的月度用量可独立查看
- 部署时间：1名开发者在 20 小时内完成集成

---

## 3. MVP Scope (In)

1. **Claude Code CLI 非交互模式集成** — 用 `claude --print` 替代直接 API 调用，利用 Max Plan 订阅
2. **OpenClaw ACP Harness 接入** — 使用 OpenClaw 的 `runtime: "acp"` + Claude Code harness 作为 Agent 底层
3. **Claude Code SDK 适配层** — 封装 `@anthropic-ai/claude-code` 的 `query()` 函数，提供统一接口
4. **成本监控 Dashboard** — 追踪各 Agent 的调用次数、响应时间、速率限制触发情况
5. **自动降级策略** — 订阅速率限制时自动回退至 API 调用，保障任务连续性

---

## 4. Out of Scope

- 支持非 Anthropic 模型的统一网关（超出本期范围）
- 对外 SaaS 化（本期是 OPC 内部工具）
- 自动化账单支付和 Stripe 集成
- Claude Code 订阅账号的自动申请/管理
- 对 Claude Code GUI 界面的依赖（仅使用 CLI/SDK）

---

## 5. User Flow (Happy Path)

```
Agent 任务触发
    ↓
调用 ClaudeGateway.query(prompt, agentId)
    ↓
Gateway 检查速率状态
    ├── 订阅余量充足 → 走 Claude Code SDK（订阅计费）
    └── 速率受限 → 走 Anthropic API 直连（token 计费）
    ↓
返回响应 + 记录用量日志
    ↓
Dashboard 更新 Agent 用量统计
```

---

## 6. Functional Requirements (P0 only)

| ID | 需求 | 优先级 |
|----|------|--------|
| F1 | Claude Code CLI 非交互调用：`claude --print "prompt"` 封装为 JS/Python 函数 | P0 |
| F2 | OpenClaw ACP session 创建：`sessions_spawn(runtime:"acp", agentId:"claude-code")` | P0 |
| F3 | Claude Code SDK query() 封装：支持 system prompt、max tokens、tool 参数透传 | P0 |
| F4 | 速率限制检测：捕获 429 响应，自动标记为"订阅受限" | P0 |
| F5 | API 降级回退：受限时自动切换至 `ANTHROPIC_API_KEY` 直连 | P0 |
| F6 | 用量日志记录：每次调用记录 agentId、timestamp、token 数、走哪条路径 | P0 |
| F7 | 环境变量管理：`CLAUDE_SUBSCRIPTION_MODE=true/false` 控制默认路由 | P0 |

---

## 7. Minimal Data Model

```
usage_logs
├── id (uuid)
├── agent_id (string)          -- e.g. "xiaoma", "xiaoyan"
├── timestamp (datetime)
├── prompt_tokens (int)
├── completion_tokens (int)
├── route (enum: subscription|api)  -- 走哪条路径
├── latency_ms (int)
├── rate_limited (bool)
└── error (string, nullable)

rate_limit_state
├── agent_id (string)
├── last_limited_at (datetime)
├── consecutive_limits (int)
└── cooldown_until (datetime)
```

---

## 8. API / Integration Notes

### Claude Code SDK 调用方式

```typescript
// 方案 A：SDK query() 函数（推荐）
import { query } from "@anthropic-ai/claude-code";

const response = await query({
  prompt: "your prompt here",
  options: {
    maxTurns: 1,
    systemPrompt: "You are a helpful assistant"
  }
});

// 方案 B：CLI --print 非交互模式
import { execSync } from "child_process";
const result = execSync(`claude --print "${prompt}"`).toString();
```

### OpenClaw ACP Harness 接入

```javascript
// 通过 sessions_spawn 创建 Claude Code session
await sessions_spawn({
  runtime: "acp",
  agentId: "claude-code",
  mode: "task",
  input: prompt
});
```

### 降级路由逻辑

```typescript
class ClaudeGateway {
  async query(prompt: string, agentId: string) {
    if (this.isRateLimited(agentId)) {
      return this.callDirectAPI(prompt);  // 直接 API
    }
    try {
      return await this.callSubscription(prompt);  // SDK
    } catch (e) {
      if (e.status === 429) {
        this.markRateLimited(agentId);
        return this.callDirectAPI(prompt);  // 降级
      }
      throw e;
    }
  }
}
```

---

## 9. Acceptance Criteria

| 场景 | 预期结果 |
|------|----------|
| 订阅模式下正常调用 | `route=subscription`，响应 < 30s，日志记录完整 |
| 触发 429 速率限制 | 自动降级到 API，`rate_limited=true`，任务不中断 |
| 8 个 Agent 并发调用 | 成功率 ≥ 95%，无任务失败 |
| Dashboard 查询 | 各 Agent 用量准确，延迟 < 500ms |
| 环境变量切换 | `CLAUDE_SUBSCRIPTION_MODE=false` 时全走 API |

---

## 10. Delivery Plan

### Milestone 1 — CLI/SDK 封装层（Week 1，约 6h）

**目标：** 验证 Claude Code SDK 可用，并封装为统一接口

**文件清单：**
- `lib/claude-gateway/index.ts` — 主入口，路由逻辑
- `lib/claude-gateway/subscription-client.ts` — Claude Code SDK 封装
- `lib/claude-gateway/api-client.ts` — Anthropic API 直连封装
- `lib/claude-gateway/rate-limiter.ts` — 速率限制状态管理
- `.env.example` — 环境变量说明

**Exit Criteria：**
- `await gateway.query("hello", "test-agent")` 返回正确响应
- 手动触发 429 时自动降级，日志中 `route=api`
- 单测通过：`npm test lib/claude-gateway`

---

### Milestone 2 — 用量日志 + OpenClaw 集成（Week 2，约 8h）

**目标：** 接入 OPC 各 Agent，记录真实用量数据

**文件清单：**
- `lib/claude-gateway/logger.ts` — 用量日志写入（SQLite 或 JSON 文件）
- `config/agents.json` — Agent ID 和限速配置
- `scripts/inject-gateway.sh` — 为各 Agent workspace 注入 gateway 配置
- `openclaw.config.js` — OpenClaw ACP harness 配置更新

**Exit Criteria：**
- 小码、小研、小策 3 个 Agent 通过 Gateway 调用 Claude
- `logs/usage.jsonl` 记录每次调用详情
- OpenClaw ACP session 可正常创建并完成任务

---

### Milestone 3 — 监控 Dashboard + 成本报告（Week 3，约 6h）

**目标：** 可视化各 Agent 用量，验证成本节省

**文件清单：**
- `dashboard/index.html` — 简单 HTML Dashboard（无需框架）
- `dashboard/api/stats.ts` — 用量统计 API
- `scripts/cost-report.py` — 月度成本对比报告生成器
- `docs/integration-guide.md` — 其他 Agent 接入说明

**Exit Criteria：**
- Dashboard 显示各 Agent 的调用次数、订阅/API 分布、估算成本
- `python scripts/cost-report.py --month 2026-04` 输出 API vs 订阅成本对比
- 运行 30 天后，订阅路径占比 ≥ 70%

---

## 11. Risks & Mitigations

| 风险 | 可能性 | 影响 | 应对方案 |
|------|--------|------|----------|
| Claude Code 订阅政策变更（如再次移除 Pro 中的访问） | 中 | 高 | 保持 API 降级路径，订阅仅作主路径 |
| Max Plan ($100) 速率不足以支撑 8 Agent 并发 | 高 | 中 | 测试实际速率；不足时升级至 $200 或混合 API |
| Claude Code SDK 版本不稳定 | 低 | 中 | 锁定 SDK 版本，定期评估升级 |
| 订阅绑定个人账号，团队共享受限 | 中 | 高 | 调研企业账号方案；或多账号轮转 |

---

## 12. Chargeability Rationale

本方案作为 OPC 内部工具，直接节省 Claude API 费用：若每月 API 花费 $500+，切换至 Claude Max $100-200/月 + 本 Gateway，净节省 ≥ $300/月，ROI 显著。若对外提供为 SaaS，定价 $49/workspace/month，目标客户为运营 8+ Agent 的 AI 团队，市场明确，willingness-to-pay 已由 Reddit 数据验证（用户已在为 Claude Max 付费，需要的是管理层）。
