架构整改:收口分层边界、统一异常体系、规范文档约定

【止血】
- errors.py: NotLoggedInError.__init__ 增加可选 message 参数,修复
  services/sealai/auth_service.py 中 raise NotLoggedInError(f"...") 导致
  TypeError 的硬错误

【边界收口】
- services/sealai/auth_service.py: 新增 get_whoami(),封装 api.sealai.get_me,
  消灭 commands/server 对 api 层的直接穿透
- commands/sealai/whoami.py: 改用 services.sealai.get_whoami(),去掉 api 层导入
- server/sealai_router.py /me: 改用 services.sealai.get_whoami(),去掉 api 层导入
- services/agent_service.py: 新增 list_agents_cmd 等 _cmd 系列便捷函数,
  commands 层无需再 import get_client
- commands/agent/list.py: 改用 list_agents_cmd(),去掉对 api.get_client 的直接依赖

【Schema 归属】
- api/sealai/schemas.py: 新增「Server 请求模型」节,迁入 sealai_router.py 中
  原有 6 个内联 BaseModel(RuleCreateRequest 等)
- server/sealai_router.py: 去掉所有内联 BaseModel 和 pydantic 导入,
  改从 api/sealai/schemas 统一导入

【导出统一】
- services/__init__.py: 纳入 SealAI 子域的全部 service 函数,
  消灭两套并行导出体系;补充模块 docstring

【工程纪律】
- commands/auth.py: 去掉 auth_use / auth_whoami 中的局部异常捕获,
  统一由 CLI 入口全局 handler 处理

【文档规范】
- CLAUDE.md: 新增「文档规范」节,明确 {module}.readme.md / {module}.test.py /
  README.{dirname}.md 命名约定及分层导入禁止规则
- 新建 README.commands.md / README.server.md / README.services.md /
  services/sealai/README.sealai.md / api/sealai/README.sealai.md
This commit is contained in:
gitea committed 2026-04-15 17:41:02 +08:00
1 parent 1fc6c75f13
commit 19f6c02c2c
16 files changed
+463 -77

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
# services/ — 业务逻辑层
## 职责边界
- **唯一业务入口**:CLI 和 HTTP Server 共用这一层,所有业务编排在此完成。
- **参数校验**:输入合法性检查(枚举值、范围、唯一性),不合法则抛 `EkbError` 子类。
- **多步编排**:如 `check_name → save`、`get → merge → save` 等组合调用。
- **不关心渲染**:只抛异常,不打印;不关心上层是 CLI 还是 Server。
## 目录结构
```
services/
├── __init__.py # 统一 re-export(快报主站 + SealAI 子域)
├── auth_service.py # 企业认证配置管理(~/.config/ekb-cli/config.json)
├── agent_service.py # Agent CRUD + 复制 + 高阶组合查询 + CLI _cmd 便捷函数
├── rule_service.py # Rule 查询(按编码/ID)+ CRUD
└── sealai/ # SealAI 子平台服务,见 README.sealai.md
```
## 依赖约定
```
services/* → api/* ✅ 允许
services/* → config.py ✅ 允许
services/* → errors.py ✅ 允许
```
## 导入约定
上层(commands/server)统一从 `services` 顶层导入:
```python
from ekb_cli.services import list_agents, list_agents_cmd
from ekb_cli.services.sealai import get_whoami
```
## CLI 便捷函数(`_cmd` 后缀)
`agent_service.py` 提供 `list_agents_cmd()` 等便捷函数,内部自行管理 `EkbClient`
的创建和关闭,使 CLI 层无需 `import get_client`,保持边界清晰。
Server 端通过 FastAPI 依赖注入(`deps.py`)获取 client,不使用 `_cmd` 系列函数。
## 异常规范
只抛 `errors.py` 中的 `EkbError` 子类:
| 场景 | 异常类 |
|---|---|
| 未登录/未配置 | `NotLoggedInError` |
| 认证过期 | `AuthenticationError` |
| 资源不存在 | `NotFoundError(resource, ref)` |
| 名称冲突 | `ConflictError(message)` |
| 参数校验失败 | `InputError(message)` |
| 快报 API 业务错误 | `ApiResponseError(api_code, msg)` |
+38
View File
@@ -2,6 +2,11 @@
commands / server 从此处导入所有 service 函数,
内部模块拆分对上层透明。
导入约定:
- 快报主站服务:from ekb_cli.services import ...
- SealAI 服务: from ekb_cli.services import sealai_xxx 或
from ekb_cli.services.sealai import xxx(子域直接导入亦可)
"""
from ekb_cli.services.auth_service import ( # noqa: F401
@@ -26,6 +31,14 @@ from ekb_cli.services.agent_service import ( # noqa: F401
update_agent,
delete_agent,
get_dedup_rules_across_agents,
# CLI 便捷函数(自管 client 生命周期,commands/* 层使用)
list_agents_cmd,
get_agent_cmd,
create_agent_cmd,
copy_agent_cmd,
update_agent_cmd,
delete_agent_cmd,
get_dedup_rules_across_agents_cmd,
)
from ekb_cli.services.rule_service import ( # noqa: F401
VALID_LEVELS,
@@ -34,3 +47,28 @@ from ekb_cli.services.rule_service import ( # noqa: F401
create_rule,
update_rule,
)
# SealAI 子域服务:通过 services.sealai 子包统一导出,
# commands/server 使用 `from ekb_cli.services.sealai import xxx`
# 此处仅做显式 re-export 以便 IDE 跳转和 import lint 检查。
from ekb_cli.services.sealai import ( # noqa: F401
get_sealai_client,
get_bearer_token,
invalidate_token,
get_whoami,
query_billing_status,
get_feature_usage,
get_draft_rules,
add_draft_rule,
edit_draft_rule,
remove_draft_rule,
get_published_versions,
publish_draft_rules,
get_preference,
update_decision_preferences,
save_preference,
get_articles,
get_article_detail,
add_article,
edit_article,
)
+47 -1
View File
@@ -13,7 +13,7 @@ CLI 和 Server 共用同一套逻辑,只有输出格式不同。
from dataclasses import dataclass, field
from typing import Optional
from ekb_cli.api import EkbClient
from ekb_cli.api import EkbClient, get_client
from ekb_cli.api import (
check_agent_name as api_check_name,
list_agents as api_list_agents,
@@ -215,3 +215,49 @@ def get_dedup_rules_across_agents(client: EkbClient) -> list[AgentRuleRef]:
rules.append(r)
return rules
# ── CLI 便捷函数(自管 client 生命周期)────────────────────────
# commands/* 层调用这批函数,不需要自行 import get_client,
# 保持 commands → services → api 的依赖方向。
def list_agents_cmd() -> PageData[AgentSummary]:
"""CLI 便捷函数:自动获取当前企业 client 并列出所有 Agent"""
with get_client() as client:
return list_agents(client)
def get_agent_cmd(agent_id: str) -> AgentDetail:
"""CLI 便捷函数:自动获取当前企业 client 并获取 Agent 详情"""
with get_client() as client:
return get_agent(client, agent_id)
def create_agent_cmd(inp: AgentCreateInput) -> AgentDetail:
"""CLI 便捷函数:自动获取当前企业 client 并新建 Agent"""
with get_client() as client:
return create_agent(client, inp)
def copy_agent_cmd(agent_id: str) -> tuple[AgentDetail, AgentDetail]:
"""CLI 便捷函数:自动获取当前企业 client 并复制 Agent"""
with get_client() as client:
return copy_agent(client, agent_id)
def update_agent_cmd(inp: AgentUpdateInput) -> AgentDetail:
"""CLI 便捷函数:自动获取当前企业 client 并更新 Agent"""
with get_client() as client:
return update_agent(client, inp)
def delete_agent_cmd(agent_id: str) -> AgentDetail:
"""CLI 便捷函数:自动获取当前企业 client 并删除 Agent"""
with get_client() as client:
return delete_agent(client, agent_id)
def get_dedup_rules_across_agents_cmd() -> list[AgentRuleRef]:
"""CLI 便捷函数:自动获取当前企业 client 并返回去重规则列表"""
with get_client() as client:
return get_dedup_rules_across_agents(client)
@@ -0,0 +1,54 @@
# services/sealai/ — SealAI 子平台业务逻辑层
## 职责边界
SealAI 是独立于快报主站的 Next.js 平台(`{corpId}.sealai.cc`),认证体系完全独立。
本子包封装所有 SealAI 相关业务逻辑,对外隐藏 `api/sealai/` 传输层细节。
## 模块说明
| 模块 | 职责 |
|---|---|
| `auth_service.py` | SSO token 换取、缓存、刷新;`get_sealai_client()`;`get_whoami()` |
| `billing_service.py` | 订阅状态查询;单功能配额查询 |
| `rules_service.py` | 草稿区审核规则 CRUD;版本发布 |
| `preference_service.py` | AI 审批风格偏好读写 |
| `knowledge_service.py` | 知识文档(Articles)CRUD |
## 认证流程
```
快报 accesstoken(三 Header 认证)
→ GET {corpId}.sealai.cc/api/auth/oauth2/session/oem-hosecloud?token=...&returnToken=1
→ Bearer JWT(缓存至 ~/.config/ekb-cli/sealai_tokens.json,TTL 3600s)
→ SealAiClient(corp_id, bearer_token)
```
缓存格式:
```json
{ "ID01Jdq2yIDnMr": { "token": "...", "fetched_at": 1712345678 } }
```
## 对外接口(统一从 `services.sealai` 导入)
```python
from ekb_cli.services.sealai import (
get_sealai_client, # 获取 SealAiClient(自动换取/刷新 token)
get_bearer_token, # 获取 Bearer JWT 字符串
invalidate_token, # 清除本地缓存 token(401 后调用)
get_whoami, # 查询当前用户身份(封装 api.sealai.get_me)
query_billing_status,
get_draft_rules, add_draft_rule, edit_draft_rule, remove_draft_rule,
get_published_versions, publish_draft_rules,
get_preference, update_decision_preferences, save_preference,
get_articles, get_article_detail, add_article, edit_article,
)
```
## 导入约定
```
services/sealai/* → api/sealai/* ✅ 允许
commands/* → api/sealai/* ❌ 禁止(必须通过 services 层)
server/* → api/sealai/* ❌ 禁止(必须通过 services 层)
```
+2
View File
@@ -4,6 +4,7 @@ from ekb_cli.services.sealai.auth_service import (
get_sealai_client,
get_bearer_token,
invalidate_token,
get_whoami,
)
from ekb_cli.services.sealai.billing_service import (
query_billing_status,
@@ -33,6 +34,7 @@ __all__ = [
"get_sealai_client",
"get_bearer_token",
"invalidate_token",
"get_whoami",
"query_billing_status",
"get_feature_usage",
"get_draft_rules",
+16 -1
View File
@@ -1,6 +1,6 @@
"""SealAI 认证业务逻辑层。
职责:SSO 换 Bearer token、本地缓存、自动刷新、对外暴露 get_sealai_client()。
职责:SSO 换 Bearer token、本地缓存、自动刷新、对外暴露 get_sealai_client() 和 get_whoami()。
认证流程:
快报 accesstoken
@@ -22,6 +22,8 @@ import httpx
from ekb_cli import config as ekb_config
from ekb_cli.errors import NotLoggedInError, AuthenticationError, ApiResponseError
from ekb_cli.api.sealai.client import SealAiClient
from ekb_cli.api.sealai.auth_api import get_me as api_get_me
from ekb_cli.api.sealai.schemas import MeData
_TOKEN_CACHE_PATH = Path.home() / ".config" / "ekb-cli" / "sealai_tokens.json"
@@ -107,3 +109,16 @@ def get_sealai_client(corp_id: str | None = None, force_refresh: bool = False) -
token = get_bearer_token(corp_id, force_refresh=force_refresh)
return SealAiClient(corp_id=corp_id, bearer_token=token)
def get_whoami(corp_id: str | None = None, force_refresh: bool = False) -> MeData:
"""查询当前 SealAI 用户身份及租户信息。
封装 api.sealai.get_me,commands/server 统一调用此函数,不直接调用 api 层。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
force_refresh: 强制刷新 Bearer token
"""
client = get_sealai_client(corp_id=corp_id, force_refresh=force_refresh)
return api_get_me(client)