架构整改:收口分层边界、统一异常体系、规范文档约定
【止血】
- 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:
1 parent
1fc6c75f13
commit
19f6c02c2c
16 files changed
+463
-77
No files matched your search
@@ -237,3 +237,38 @@ POST /api/engine/hab/agent/rule/delete # 删除规则(POST,非
|
||||
- 枚举常量、字段语义写在命令组 README,不写在本文件
|
||||
- `services/` 层只抛出 `EkbError` 子类,不关心如何渲染;
|
||||
CLI 层用 rich 红字,Server 层转 HTTP 状态码
|
||||
|
||||
## 文档规范
|
||||
|
||||
每个源文件和目录都应该有配套的说明文档,命名规则如下:
|
||||
|
||||
### 文件级文档(`{module}.readme.md`)
|
||||
|
||||
- 每个 `demo.py` 对应一份 `demo.readme.md`,记录:
|
||||
- 枚举常量的取值含义(不要散落在代码注释里)
|
||||
- 模式选择的决策依据(为什么这么设计)
|
||||
- 对外暴露的函数/类的使用约定
|
||||
- 不要把这些内容写进 CLAUDE.md,保持各自归属
|
||||
|
||||
### 测试文件(`{module}.test.py`,可选)
|
||||
|
||||
- 每个 `demo.py` 可以有 `demo.test.py` 作为配套测试
|
||||
- 测试文件与被测模块放在同一目录
|
||||
- 最外层独立模块(`config.py`、`errors.py`)的测试**暂时可以忽略**
|
||||
|
||||
### 目录级文档(`README.{dirname}.md`)
|
||||
|
||||
- 每个含 `__init__.py` 的目录应有目录级说明文档
|
||||
- 命名约定:`README.{dirname}.md`(如 `README.services.md`、`README.server.md`)
|
||||
- 内容包括:该层的职责边界、组织方式、模块间的调用约定
|
||||
|
||||
### 分层导入约束(硬规则)
|
||||
|
||||
以下导入关系**严格禁止**,违反则视为边界穿透:
|
||||
|
||||
| 禁止的方向 | 说明 |
|
||||
|---|---|
|
||||
| `commands/*` → `api/*` | CLI 表现层不得直接调用传输层 |
|
||||
| `server/*` → `api/*`(业务函数) | Server 路由不得直接调用 API 域函数(`deps.py` 中的 `get_client` 除外) |
|
||||
|
||||
正确路径:`commands/*` → `services/*` → `api/*`
|
||||
@@ -0,0 +1,48 @@
|
||||
# api/sealai/ — SealAI 传输层
|
||||
|
||||
## 职责边界
|
||||
|
||||
- **薄层封装**:只做 HTTP 请求发送和 Pydantic 响应解析,不做业务判断。
|
||||
- **不被上层直接调用**:仅供 `services/sealai/` 调用,commands 和 server 不得直接引用本层业务函数。
|
||||
|
||||
## 模块说明
|
||||
|
||||
| 模块 | 封装的 API |
|
||||
|---|---|
|
||||
| `client.py` | `SealAiClient`:Bearer JWT 认证的 httpx 客户端 |
|
||||
| `schemas.py` | 所有 Pydantic 模型(响应模型 + Server 请求模型) |
|
||||
| `auth_api.py` | `GET /api/v1/auth/me` → `get_me()` |
|
||||
| `billing_api.py` | `GET /api/v1/billing/status` → `get_billing_status()` |
|
||||
| `rules_api.py` | `/api/v1/rules` 系列(草稿 CRUD + 版本发布) |
|
||||
| `preference_api.py` | `GET/POST /api/v1/agent/ai-approval/config` |
|
||||
| `knowledge_api.py` | `/api/v1/knowledge/articles` 系列 |
|
||||
|
||||
## SealAiClient
|
||||
|
||||
```python
|
||||
class SealAiClient:
|
||||
base_url: str # https://{corp_id.lower()}.sealai.cc
|
||||
bearer_token: str
|
||||
```
|
||||
|
||||
所有 API 函数签名:`fn(client: SealAiClient, ...) -> ResponseModel`
|
||||
|
||||
## schemas.py 结构
|
||||
|
||||
```
|
||||
schemas.py
|
||||
├── 通用包装:SealAiResponse[T]
|
||||
├── 认证:SealAiUser / SealAiTenant / MeData
|
||||
├── 计费:Subscription / Feature / BillingStatusData
|
||||
├── 审核规则草稿:DraftRule / DraftRulesData
|
||||
├── 已发布版本:RuleSetVersion / PublishVersionData
|
||||
├── 风格偏好:DecisionPreferences / AiApprovalConfig / AiApprovalSaveResult
|
||||
├── 知识文档:KnowledgeArticle / KnowledgeArticleListData
|
||||
└── Server 请求模型:RuleCreateRequest / RuleUpdateRequest /
|
||||
PublishVersionRequest / DecisionPreferencesUpdateRequest /
|
||||
ArticleCreateRequest / ArticleUpdateRequest
|
||||
```
|
||||
|
||||
## 已知 API 路径
|
||||
|
||||
详见 `services/sealai/README.sealai.md` 及各 `*_api.py` 文件顶部 docstring。
|
||||
@@ -296,3 +296,56 @@ class KnowledgeArticleListData(BaseModel):
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
# ── Server 请求模型(FastAPI 路由入参,统一在此维护)──────────────────────────
|
||||
# 命名规则:{功能}{动作}Request,只在 server/sealai_router.py 中引用。
|
||||
|
||||
class RuleCreateRequest(BaseModel):
|
||||
"""POST /sealai/rules 请求体"""
|
||||
description: str
|
||||
scope: str
|
||||
strictness: str = "MUST_FOLLOW"
|
||||
|
||||
|
||||
class RuleUpdateRequest(BaseModel):
|
||||
"""PUT /sealai/rules/{rule_id} 请求体(partial,字段均可选)"""
|
||||
description: Optional[str] = None
|
||||
scope: Optional[str] = None
|
||||
strictness: Optional[str] = None
|
||||
|
||||
|
||||
class PublishVersionRequest(BaseModel):
|
||||
"""POST /sealai/rule-set-versions/publish 请求体"""
|
||||
version_name: str
|
||||
|
||||
|
||||
class DecisionPreferencesUpdateRequest(BaseModel):
|
||||
"""PATCH /sealai/preference/decision 请求体(patch 式,字段均可选)"""
|
||||
explicit_approve: Optional[str] = None
|
||||
explicit_reject: Optional[str] = None
|
||||
exempt_approve: Optional[str] = None
|
||||
review: Optional[str] = None
|
||||
|
||||
|
||||
class ArticleCreateRequest(BaseModel):
|
||||
"""POST /sealai/knowledge/articles 请求体"""
|
||||
title: str
|
||||
purpose: str
|
||||
content: str
|
||||
content_type: str = "policy"
|
||||
status: str = "published"
|
||||
scenarios: list[str] = []
|
||||
tags: list[str] = []
|
||||
|
||||
|
||||
class ArticleUpdateRequest(BaseModel):
|
||||
"""PATCH /sealai/knowledge/articles/{article_id} 请求体(partial,字段均可选)"""
|
||||
title: Optional[str] = None
|
||||
purpose: Optional[str] = None
|
||||
content: Optional[str] = None
|
||||
content_type: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
enabled: Optional[bool] = None
|
||||
scenarios: Optional[list[str]] = None
|
||||
tags: Optional[list[str]] = None
|
||||
@@ -0,0 +1,35 @@
|
||||
# commands/ — CLI 表现层
|
||||
|
||||
## 职责边界
|
||||
|
||||
- **只做 I/O 适配**:参数解析(typer)、交互式输入、rich 格式化输出。
|
||||
- **不做业务编排**:调用 `services.*` 完成,不直接调用 `api.*`。
|
||||
- **不做异常处理**:让 `EkbError` 自然冒泡至 CLI 入口(`__init__.py`)的全局 handler;
|
||||
命令内部**不应**局部 catch 再重新打印,以免造成双重输出或消息漂移。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
commands/
|
||||
├── auth.py # ekb auth 命令组(企业认证管理)
|
||||
├── help.py # ekb commands(命令树速查)
|
||||
├── serve.py # ekb serve(启动 HTTP API Server)
|
||||
├── agent/ # ekb agent 命令组,见 README.agent.md / README.rule.md
|
||||
└── sealai/ # ekb sealai 命令组,见 README.sealai.md
|
||||
```
|
||||
|
||||
## 依赖约定
|
||||
|
||||
```
|
||||
commands/* → services/* ✅ 允许
|
||||
commands/* → api/* ❌ 禁止(边界穿透)
|
||||
```
|
||||
|
||||
## 新增命令流程
|
||||
|
||||
1. 在对应子目录新建 `{verb}.py`,只写展示逻辑
|
||||
2. 在 `{dir}/__init__.py` 注册到 typer app
|
||||
3. 在 `services/` 添加或复用业务函数
|
||||
4. 在 `server/` 对应 router 添加 HTTP 端点
|
||||
5. 更新 `help.py` 命令树
|
||||
6. 更新 `CLAUDE.md` 命令全图和接口对照表
|
||||
@@ -5,8 +5,7 @@ from rich.console import Console
|
||||
from rich.table import Table
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli.api import get_client
|
||||
from ekb_cli.services import list_agents
|
||||
from ekb_cli.services import list_agents_cmd
|
||||
|
||||
console = Console()
|
||||
STATE_MAP = {0: "[dim]草稿[/dim]", 1: "[green]已发布[/green]"}
|
||||
@@ -15,8 +14,7 @@ MODE_MAP = {0: "全自动", 1: "半自动", 2: "辅助"}
|
||||
|
||||
def cmd_list():
|
||||
"""列出所有智能审核 Agent"""
|
||||
with get_client() as client:
|
||||
page = list_agents(client)
|
||||
page = list_agents_cmd()
|
||||
|
||||
if not page.items:
|
||||
rprint("[yellow]暂无 Agent[/yellow]")
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
表现层:只负责参数解析、交互式输入、rich 格式化输出。
|
||||
业务逻辑委托给 services.auth_service。
|
||||
|
||||
异常处理约定:
|
||||
所有命令不做局部捕获,让 EkbError 冒泡到 CLI 入口的全局 handler,
|
||||
由 __init__.py 统一以红字输出并 Exit(1)。
|
||||
"""
|
||||
|
||||
import typer
|
||||
@@ -62,13 +66,8 @@ def auth_list():
|
||||
@app.command("use")
|
||||
def auth_use(corp_id: str = typer.Argument(..., help="要切换的企业 corpId")):
|
||||
"""切换当前使用的企业"""
|
||||
from ekb_cli.errors import EkbError
|
||||
try:
|
||||
corp = auth_service.use_corp(corp_id)
|
||||
rprint(f"[green]✓[/green] 已切换到企业 [bold]{corp.name}[/bold] ({corp.corp_id})")
|
||||
except EkbError as e:
|
||||
rprint(f"[red]{e.message}[/red]")
|
||||
raise typer.Exit(1)
|
||||
corp = auth_service.use_corp(corp_id)
|
||||
rprint(f"[green]✓[/green] 已切换到企业 [bold]{corp.name}[/bold] ({corp.corp_id})")
|
||||
|
||||
|
||||
@app.command("remove")
|
||||
@@ -81,10 +80,5 @@ def auth_remove(corp_id: str = typer.Argument(..., help="要删除的企业 corp
|
||||
@app.command("whoami")
|
||||
def auth_whoami():
|
||||
"""查看当前使用的企业"""
|
||||
from ekb_cli.errors import NotLoggedInError
|
||||
try:
|
||||
corp = auth_service.whoami()
|
||||
rprint(f"当前企业:[bold]{corp.name}[/bold] ({corp.corp_id})")
|
||||
except NotLoggedInError:
|
||||
rprint("[yellow]未登录,请先执行 `ekb auth add`[/yellow]")
|
||||
raise typer.Exit(1)
|
||||
corp = auth_service.whoami()
|
||||
rprint(f"当前企业:[bold]{corp.name}[/bold] ({corp.corp_id})")
|
||||
@@ -1,16 +1,15 @@
|
||||
"""sealai whoami:查看当前 SealAI 用户身份
|
||||
|
||||
表现层:只负责 rich 格式化输出。
|
||||
业务逻辑委托给 services.sealai.auth_service。
|
||||
业务逻辑(含 get_me 调用)完全委托给 services.sealai.get_whoami,
|
||||
不直接导入 api 层任何函数。
|
||||
"""
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli.services.sealai import get_sealai_client, get_bearer_token
|
||||
from ekb_cli.api.sealai import get_me
|
||||
from ekb_cli.services.sealai import get_whoami
|
||||
|
||||
console = Console()
|
||||
|
||||
@@ -20,8 +19,7 @@ def cmd_whoami(
|
||||
refresh: bool = typer.Option(False, "--refresh", help="强制刷新 SealAI Bearer token"),
|
||||
):
|
||||
"""查看当前 SealAI 用户身份及租户信息"""
|
||||
client = get_sealai_client(corp_id=corp_id, force_refresh=refresh)
|
||||
me = get_me(client)
|
||||
me = get_whoami(corp_id=corp_id, force_refresh=refresh)
|
||||
|
||||
user = me.user
|
||||
tenant = me.tenant
|
||||
|
||||
@@ -18,10 +18,16 @@ class EkbError(Exception):
|
||||
|
||||
|
||||
class NotLoggedInError(EkbError):
|
||||
"""未登录/未配置认证"""
|
||||
"""未登录/未配置认证。
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__("未登录,请先执行 `ekb auth add` 添加企业认证", code=401)
|
||||
可传入自定义 message 说明具体是哪个企业未配置;
|
||||
不传则使用通用提示,引导用户执行 `ekb auth add`。
|
||||
"""
|
||||
|
||||
_DEFAULT = "未登录,请先执行 `ekb auth add` 添加企业认证"
|
||||
|
||||
def __init__(self, message: str | None = None) -> None:
|
||||
super().__init__(message or self._DEFAULT, code=401)
|
||||
|
||||
|
||||
class AuthenticationError(EkbError):
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# server/ — HTTP API Server(表现层)
|
||||
|
||||
## 职责边界
|
||||
|
||||
- **只做 HTTP 适配**:路由注册、Query/Body 参数绑定、JSON 序列化、HTTP 状态码映射。
|
||||
- **不做业务编排**:调用 `services.*` 完成,路由函数体保持简短。
|
||||
- **不定义请求/响应模型**:所有 `BaseModel` 子类统一放在对应的 `schemas.py` 中,
|
||||
路由文件只做 import,不在文件内 inline 定义。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
server/
|
||||
├── __init__.py # create_app() 工厂;全局 EkbError → HTTP 异常处理器
|
||||
├── deps.py # FastAPI 依赖注入:ClientDep(EkbClient)
|
||||
├── auth_router.py # /auth/* 路由
|
||||
├── agent_router.py # /agents/* 路由
|
||||
├── rule_router.py # /rules/* 路由
|
||||
└── sealai_router.py # /sealai/* 路由
|
||||
```
|
||||
|
||||
## 依赖约定
|
||||
|
||||
```
|
||||
server/* → services/* ✅ 允许
|
||||
server/deps.py → api.get_client ✅ 允许(专属基础设施职责)
|
||||
server/* → api.*(业务函数) ❌ 禁止(边界穿透)
|
||||
```
|
||||
|
||||
## 请求模型归属规则
|
||||
|
||||
| 模型类型 | 存放位置 |
|
||||
|---|---|
|
||||
| 快报 API 响应模型 | `api/schemas.py` |
|
||||
| SealAI API 响应模型 | `api/sealai/schemas.py` |
|
||||
| Server 请求/响应模型 | 同上,在文件末尾「Server 请求模型」节 |
|
||||
|
||||
## 异常处理
|
||||
|
||||
`server/__init__.py` 中注册了全局 handler:
|
||||
|
||||
- `EkbError` → `code` 字段映射 HTTP 状态码,`message` 字段作为 `detail` 返回
|
||||
- 路由函数内**不应**局部 catch `EkbError`
|
||||
|
||||
## Swagger UI
|
||||
|
||||
Server 启动后访问:`http://127.0.0.1:9528/docs`
|
||||
@@ -22,10 +22,10 @@
|
||||
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Query
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ekb_cli.services.sealai import (
|
||||
get_sealai_client,
|
||||
get_whoami,
|
||||
query_billing_status,
|
||||
get_draft_rules,
|
||||
add_draft_rule,
|
||||
@@ -41,7 +41,6 @@ from ekb_cli.services.sealai import (
|
||||
add_article,
|
||||
edit_article,
|
||||
)
|
||||
from ekb_cli.api.sealai import get_me
|
||||
from ekb_cli.api.sealai.schemas import (
|
||||
MeData,
|
||||
BillingStatusData,
|
||||
@@ -53,6 +52,13 @@ from ekb_cli.api.sealai.schemas import (
|
||||
AiApprovalSaveResult,
|
||||
KnowledgeArticle,
|
||||
KnowledgeArticleListData,
|
||||
# Server 请求模型
|
||||
RuleCreateRequest,
|
||||
RuleUpdateRequest,
|
||||
PublishVersionRequest,
|
||||
DecisionPreferencesUpdateRequest,
|
||||
ArticleCreateRequest,
|
||||
ArticleUpdateRequest,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
@@ -65,8 +71,7 @@ def sealai_whoami(
|
||||
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
|
||||
refresh: bool = Query(False, description="强制刷新 Bearer token"),
|
||||
):
|
||||
client = get_sealai_client(corp_id=corp_id, force_refresh=refresh)
|
||||
return get_me(client)
|
||||
return get_whoami(corp_id=corp_id, force_refresh=refresh)
|
||||
|
||||
|
||||
@router.get("/billing", response_model=BillingStatusData, summary="查看 SealAI 订阅状态及功能配额")
|
||||
@@ -87,12 +92,6 @@ def sealai_list_rules(
|
||||
return get_draft_rules(client)
|
||||
|
||||
|
||||
class RuleCreateRequest(BaseModel):
|
||||
description: str
|
||||
scope: str
|
||||
strictness: str = "MUST_FOLLOW"
|
||||
|
||||
|
||||
@router.post("/rules", response_model=DraftRule, summary="新建草稿审核规则")
|
||||
def sealai_create_rule(
|
||||
body: RuleCreateRequest,
|
||||
@@ -107,12 +106,6 @@ def sealai_create_rule(
|
||||
)
|
||||
|
||||
|
||||
class RuleUpdateRequest(BaseModel):
|
||||
description: str | None = None
|
||||
scope: str | None = None
|
||||
strictness: str | None = None
|
||||
|
||||
|
||||
@router.put("/rules/{rule_id}", response_model=DraftRule, summary="更新草稿审核规则(partial)")
|
||||
def sealai_update_rule(
|
||||
rule_id: str,
|
||||
@@ -152,10 +145,6 @@ def sealai_list_versions(
|
||||
return get_published_versions(client)
|
||||
|
||||
|
||||
class PublishVersionRequest(BaseModel):
|
||||
version_name: str
|
||||
|
||||
|
||||
@router.post(
|
||||
"/rule-set-versions/publish",
|
||||
response_model=PublishVersionData,
|
||||
@@ -196,13 +185,6 @@ def sealai_save_preference(
|
||||
return save_preference(client, body)
|
||||
|
||||
|
||||
class DecisionPreferencesUpdateRequest(BaseModel):
|
||||
explicit_approve: str | None = None
|
||||
explicit_reject: str | None = None
|
||||
exempt_approve: str | None = None
|
||||
review: str | None = None
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/preference/decision",
|
||||
response_model=AiApprovalSaveResult,
|
||||
@@ -248,16 +230,6 @@ def sealai_list_articles(
|
||||
)
|
||||
|
||||
|
||||
class ArticleCreateRequest(BaseModel):
|
||||
title: str
|
||||
purpose: str
|
||||
content: str
|
||||
content_type: str = "policy"
|
||||
status: str = "published"
|
||||
scenarios: list[str] = []
|
||||
tags: list[str] = []
|
||||
|
||||
|
||||
@router.post(
|
||||
"/knowledge/articles",
|
||||
response_model=KnowledgeArticle,
|
||||
@@ -293,17 +265,6 @@ def sealai_get_article(
|
||||
return get_article_detail(client, article_id)
|
||||
|
||||
|
||||
class ArticleUpdateRequest(BaseModel):
|
||||
title: Optional[str] = None
|
||||
purpose: Optional[str] = None
|
||||
content: Optional[str] = None
|
||||
content_type: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
enabled: Optional[bool] = None
|
||||
scenarios: Optional[list[str]] = None
|
||||
tags: Optional[list[str]] = None
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/knowledge/articles/{article_id}",
|
||||
response_model=KnowledgeArticle,
|
||||
|
||||
@@ -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)` |
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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 层)
|
||||
```
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user