chore: 移除旧 Python CLI 项目

删除 ekb-cli Python 项目:
- pyproject.toml, uv.lock, .python-version
- src/ekb_cli/ 完整 Python 源码
- scripts/ 辅助脚本
- tmp_test/ 临时测试文件

为迁移到 TS + Bun MCP Server 做准备
This commit is contained in:
gitea committed 2026-05-18 17:43:52 +08:00
1 parent 79af2c1363
commit 00ad09e386
92 files changed
-7238

No files matched your search

-37
View File
@@ -1,37 +0,0 @@
"""ekb-cli:快报命令行工具
入口:注册所有命令组,统一捕获 EkbError 异常。
"""
import typer
from ekb_cli.commands import auth
from ekb_cli.commands.agent import app as agent_app
from ekb_cli.commands.sealai import app as sealai_app
from ekb_cli.commands.platform import app as platform_app
from ekb_cli.commands.help import cmd_commands
from ekb_cli.commands.serve import cmd_serve
app = typer.Typer(
name="ekb",
help="快报(ekuaibao)命令行工具",
no_args_is_help=True,
)
app.add_typer(auth.app, name="auth")
app.add_typer(agent_app, name="agent")
app.add_typer(sealai_app, name="sealai")
app.add_typer(platform_app, name="platform")
app.command("commands")(cmd_commands)
app.command("serve")(cmd_serve)
def main():
"""CLI 入口:统一捕获 EkbError,输出友好错误信息"""
from ekb_cli.errors import EkbError
from rich import print as rprint
try:
app()
except EkbError as e:
rprint(f"[red]{e.message}[/red]")
raise SystemExit(1)
-84
View File
@@ -1,84 +0,0 @@
# API 层说明(`ekb_cli/api/`)
## 三层架构
```
api/
├── __init__.py # 第1层:HTTP 客户端(EkbClient)+ 统一 re-export
├── schemas.py # 第2层辅助:Pydantic 响应模型,所有接口响应在此校验
├── agent.py # 第2层:Agent 相关接口封装
└── rule.py # 第2层:Rule(审核规则)相关接口封装
```
**commands 只从 `ekb_cli.api` 导入**,内部文件如何拆分对上层透明:
```python
from ekb_cli.api import get_client, list_agents, get_agent, list_rules, ...
```
---
## `__init__.py` — HTTP 客户端
`EkbClient` 负责:带认证头(`accesstoken` / `corpid` / `staffid`)发 HTTP 请求,返回原始 JSON。它不理解业务。
| 方法 | 说明 |
|------|------|
| `get(path, **params)` | GET 请求,自动附加 `corpId` |
| `post(path, body, **params)` | POST 请求,body 为 JSON |
`get_client()` 从 `~/.config/ekb-cli/config.json` 读取当前企业认证信息,构建 `EkbClient`。
---
## `schemas.py` — Pydantic 响应模型
所有模型使用 `extra="allow"`(允许快报新增字段,但已知字段强制类型校验)。API 格式变更时,Pydantic 会抛出 `ValidationError`,精确定位到字段名。
| 模型 | 用途 |
|------|------|
| `EkbResponse[T]` | 通用响应包装(`code` / `msg` / `data`) |
| `PageData[T]` | 通用分页(`totalItems` / `items`) |
| `AgentSummary` | Agent 列表中的摘要条目(无 `agentRule`) |
| `AgentDetail` | Agent 详情(含 `agentRule` 列表) |
| `AgentRuleRef` | `AgentDetail` 中内嵌的规则完整字段 |
| `Rule` | 规则新建/更新的响应体 |
| `RuleWithAgents` | 规则列表中的条目(含 `agents` 关联摘要) |
| `RuleAgentRef` | `RuleWithAgents` 中关联 Agent 摘要(`id/name/icon`) |
---
## `agent.py` — Agent 接口
| 函数 | 方法 | 路径 | 返回 |
|------|------|------|------|
| `check_agent_name(client, name)` | GET | `/engine/hab/agent/checkName` | `bool`(`True`=可用) |
| `list_agents(client, page, size)` | GET | `/engine/hab/agent/list` | `PageData[AgentSummary]` |
| `get_agent(client, agent_id)` | GET | `/engine/hab/agent/detail` | `AgentDetail` |
| `save_agent(client, payload)` | POST | `/engine/hab/agent/save` | `AgentDetail` |
> `save_agent` 同时承担新建(无 `id`)和更新(有 `id`)。
---
## `rule.py` — Rule 接口
| 函数 | 方法 | 路径 | 返回 |
|------|------|------|------|
| `list_rules(client, page, size)` | GET | `/engine/hab/agent/rule/list` | `PageData[RuleWithAgents]` |
| `save_rule(client, payload)` | POST | `/engine/hab/agent/rule/save` | `Rule` |
| `update_rule(client, payload)` | POST | `/engine/hab/agent/rule/update` | `Rule` |
---
## 接口格式变更应对
快报前端更新后若接口格式改变,Pydantic 会在第一次调用时抛出 `ValidationError`,输出类似:
```
pydantic_core._pydantic_core.ValidationError: 1 validation error for AgentDetail
agentRule
Field required [type=missing, ...]
```
定位方式:字段名 → `schemas.py` 对应模型 → 对照实际响应 JSON 更新字段定义。
-110
View File
@@ -1,110 +0,0 @@
"""HTTP 客户端:封装对快报 API 的请求,使用 accesstoken + corpid + staffid 认证
异常约定:
- HTTP 401 → AuthenticationError
- HTTP 其他非 2xx → ApiResponseError
- 快报业务码非 200 → ApiResponseError
- 未登录(无配置)→ NotLoggedInError
"""
import httpx
from typing import Any
from ekb_cli.errors import AuthenticationError, ApiResponseError, NotLoggedInError
BASE_URL = "https://app.ekuaibao.com"
class EkbClient:
def __init__(self, corp_id: str, access_token: str, staff_id: str):
self.corp_id = corp_id
self._client = httpx.Client(
base_url=BASE_URL,
headers={
"accesstoken": access_token,
"corpid": corp_id,
"staffid": staff_id,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
"Accept": "application/json",
"Content-Type": "application/json",
"Accept-Language": "zh-CN,zh;q=0.9",
},
timeout=30,
)
def get(self, path: str, **params) -> Any:
params["corpId"] = self.corp_id
try:
resp = self._client.get(f"/api{path}", params=params)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
raise AuthenticationError()
raise ApiResponseError(e.response.status_code, str(e))
data = resp.json()
# 快报 errorCode 结构(未登录等场景)
if isinstance(data, dict) and data.get("errorCode") == 401:
raise AuthenticationError(data.get("errorMessage", "认证失败"))
return data
def post(self, path: str, body: dict = None, **params) -> Any:
params["corpId"] = self.corp_id
try:
resp = self._client.post(f"/api{path}", json=body or {}, params=params)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
raise AuthenticationError()
raise ApiResponseError(e.response.status_code, str(e))
data = resp.json()
if isinstance(data, dict) and data.get("errorCode") == 401:
raise AuthenticationError(data.get("errorMessage", "认证失败"))
return data
def __enter__(self):
return self
def __exit__(self, *args):
self._client.close()
def close(self):
self._client.close()
def get_client() -> EkbClient:
"""从当前配置获取已认证的客户端,未登录时抛出 NotLoggedInError"""
from ekb_cli import config
corp = config.get_current_corp()
if not corp:
raise NotLoggedInError()
corp_id = config.get_current_corp_id()
return EkbClient(
corp_id=corp_id,
access_token=corp["access_token"],
staff_id=corp["staff_id"],
)
# ── 统一 re-export:commands / services 只从这里导入 ──────────
from ekb_cli.api.agent import ( # noqa: E402
check_agent_name,
list_agents,
get_agent,
save_agent,
delete_agent,
)
from ekb_cli.api.rule import ( # noqa: E402
list_rules,
get_rule_detail,
save_rule,
update_rule,
delete_rule,
)
from ekb_cli.api.platform import ( # noqa: E402
list_platforms,
list_workflows,
get_workflow_stats,
get_workflow_charge,
)
-37
View File
@@ -1,37 +0,0 @@
"""Agent 相关 API 调用封装"""
from ekb_cli.api import EkbClient
from ekb_cli.api.schemas import (
AgentDetail, AgentSummary, EkbResponse, PageData
)
def check_agent_name(client: EkbClient, name: str) -> bool:
"""检查名称是否可用:True=可用,False=已存在(接口 data=false 表示可用)"""
raw = client.get("/engine/hab/agent/checkName", name=name)
EkbResponse[bool].model_validate(raw)
return not raw.get("data", False)
def list_agents(client: EkbClient, page: int = 1, size: int = 1000) -> PageData[AgentSummary]:
raw = client.get("/engine/hab/agent/list", page=page, size=size)
resp = EkbResponse[PageData[AgentSummary]].model_validate(raw)
return resp.data
def get_agent(client: EkbClient, agent_id: str) -> AgentDetail:
raw = client.get("/engine/hab/agent/detail", id=agent_id)
resp = EkbResponse[AgentDetail].model_validate(raw)
return resp.data
def save_agent(client: EkbClient, payload: dict) -> AgentDetail:
raw = client.post("/engine/hab/agent/save", payload)
resp = EkbResponse[AgentDetail].model_validate(raw)
return resp.data
def delete_agent(client: EkbClient, agent_id: str) -> None:
"""删除 Agent(state=2)"""
raw = client.get("/engine/hab/agent/active", id=agent_id, state=2)
EkbResponse[AgentDetail].model_validate(raw)
@@ -1,25 +0,0 @@
# api/platform — 自建应用域传输层
## 已实现
| 文件 | 说明 |
|---|---|
| `easo_client.py` | EASO 工作流客户端(`unity.ekuaibao.com` + Bearer JWT) |
| `platform_api.py` | 自建应用列表接口 |
| `workflow_api.py` | 工作流列表 / 统计 / 配额接口 |
## 待实现(预留)
以下模块接口尚未抓包或开发,待后续按需补充:
| 模块 | 预估接口 | 说明 |
|---|---|---|
| **业务对象(Entity)** | `POST /api/v2/datalink/entity/platformId/$id` | 获取平台下的实体/数据表列表 |
| **页面设计器** | 待抓包 | 自定义页面配置相关接口 |
| **互联卡片** | 待抓包 | 卡片配置/联动相关接口 |
| **应用变量** | 待抓包 | 全局变量定义相关接口 |
| **应用扩展** | 待抓包 | 扩展能力配置接口 |
| **应用日志** | `GET /api/easo/pipelines/logs`(运行日志) | 与工作流列表同接口,参数不同 |
| **平台凭证(Realm)** | `GET /api/v2/datalink/platform/realm` | appKey / appSecret 查询 |
新增接口时,在本目录创建对应 `xxx_api.py`,并在 `__init__.py` 补充 re-export。
-24
View File
@@ -1,24 +0,0 @@
"""api/platform 子包:自建应用域传输层统一 re-export
包含两类客户端:
- 快报主站 EkbClient(由父包 api/ 提供)→ 用于 platform_api
- EASO 客户端 EasoClient(本包提供)→ 用于 workflow_api
commands / services 只从此处导入,内部文件拆分对上层透明。
"""
from ekb_cli.api.platform.schemas import ( # noqa: F401
Platform,
Workflow,
WorkflowTask,
WorkflowPage,
WorkflowStats,
WorkflowCharge,
)
from ekb_cli.api.platform.easo_client import EasoClient, get_easo_client # noqa: F401
from ekb_cli.api.platform.platform_api import list_platforms # noqa: F401
from ekb_cli.api.platform.workflow_api import ( # noqa: F401
list_workflows,
get_workflow_stats,
get_workflow_charge,
)
-206
View File
@@ -1,206 +0,0 @@
"""EASO HTTP 客户端(传输层)。
与快报主站的 EkbClient 并列,同属 api/ 传输层。
区别:EASO 工作流子域使用 Bearer realm token 认证,域名固定为 unity.ekuaibao.com。
EASO 完整认证链路(四步,均在 get_easo_client() 内自动完成):
1. 主站 accessToken
→ GET business-center.ekuaibao.com/auth/oauth2/grant/ekb/accessToken
→ hose-access-token(长期 JWT,约 30 天)
2. 主站 accessToken + corpId/staffId Headers
→ GET app.ekuaibao.com/api/engine/realm/$UNITY/actions/jwt
→ UNITY Bearer JWT(约 2 小时,aud=UNITY)
3. UNITY JWT + hoseaccesstoken Header
→ GET unity.ekuaibao.com/api/realms/EASO?corpId=...
→ EASO realm accessToken(约 2 小时,短字符串)
4. EASO realm accessToken → Authorization: Bearer <token>
→ unity.ekuaibao.com 工作流接口(/api/easo/...)
调用方无需关心上述细节,通过 get_easo_client() 直接获取可用的 EasoClient 实例。
"""
from __future__ import annotations
import httpx
from typing import Any
from ekb_cli.errors import AuthenticationError, ApiResponseError, NotLoggedInError
EASO_BASE_URL = "https://unity.ekuaibao.com"
_EKB_BASE_URL = "https://app.ekuaibao.com"
_BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com"
_UA = (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/147.0.0.0 Safari/537.36"
)
class EasoClient:
"""EASO 工作流客户端(unity.ekuaibao.com),使用 EASO realm token 认证。"""
def __init__(
self,
corp_id: str,
access_token: str,
easo_token: str,
hose_token: str,
):
self.corp_id = corp_id
self._client = httpx.Client(
base_url=EASO_BASE_URL,
headers={
"Authorization": f"Bearer {easo_token}",
"accesstoken": access_token,
"corporationid": corp_id,
"hoseaccesstoken": hose_token,
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": _UA,
},
cookies={"hose-access-token": hose_token},
timeout=30,
)
def _handle_error(self, e: httpx.HTTPStatusError) -> None:
if e.response.status_code == 401:
raise AuthenticationError("EASO token 已过期,请重新登录")
raise ApiResponseError(e.response.status_code, str(e))
def get(self, path: str, **params) -> Any:
params["corpId"] = self.corp_id
try:
resp = self._client.get(path, params=params)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
self._handle_error(e)
data = resp.json()
if isinstance(data, dict) and data.get("errorCode") == 401:
raise AuthenticationError(data.get("errorMessage", "认证失败"))
return data
def __enter__(self):
return self
def __exit__(self, *args):
self._client.close()
def close(self):
self._client.close()
# ── 内部工具函数 ──────────────────────────────────────────────
def _fetch_hose_token(access_token: str, corp_id: str) -> str:
"""Step 1:用主站 accessToken 换取 hose-access-token(business-center JWT,约 30 天)。"""
resp = httpx.get(
f"{_BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken",
params={"corpId": corp_id, "ekbAccessToken": access_token, "environment": "app"},
timeout=10,
)
try:
resp.raise_for_status()
except httpx.HTTPStatusError as e:
raise ApiResponseError(e.response.status_code, f"hose-access-token 换取失败: {e}")
data = resp.json()
token = data.get("data", "")
if not token:
raise ApiResponseError(0, f"hose-access-token 换取失败,响应结构异常:{data}")
return token
def _fetch_unity_jwt(access_token: str, corp_id: str, staff_id: str) -> str:
"""Step 2:换取 UNITY Bearer JWT(aud=UNITY,约 2 小时)。
该 JWT 用于访问 unity.ekuaibao.com 基础接口(如 /api/store/me、/api/realms/EASO)。
"""
resp = httpx.get(
f"{_EKB_BASE_URL}/api/engine/realm/$UNITY/actions/jwt",
params={"corpId": corp_id},
headers={
"accesstoken": access_token,
"corpid": corp_id,
"staffid": staff_id,
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": _UA,
},
timeout=30,
)
try:
resp.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
raise AuthenticationError()
raise ApiResponseError(e.response.status_code, str(e))
raw = resp.json()
if isinstance(raw, dict) and raw.get("errorCode") == 401:
raise AuthenticationError(raw.get("errorMessage", "认证已过期,请重新执行 `ekb auth add` 更新 token"))
unity_jwt = raw.get("id") or raw.get("value", "")
if not unity_jwt:
raise ApiResponseError(0, f"UNITY JWT 换取失败,响应结构异常:{raw}")
return unity_jwt
def _fetch_easo_realm_token(corp_id: str, unity_jwt: str, hose_token: str) -> str:
"""Step 3:用 UNITY JWT 向 unity.ekuaibao.com 换取 EASO realm accessToken(约 2 小时)。
这是实际用于 /api/easo/... 工作流接口的短字符串 Bearer token。
"""
resp = httpx.get(
f"{EASO_BASE_URL}/api/realms/EASO",
params={"corpId": corp_id},
headers={
"Authorization": f"Bearer {unity_jwt}",
"hoseaccesstoken": hose_token,
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": _UA,
},
cookies={"hose-access-token": hose_token},
timeout=30,
)
try:
resp.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
raise AuthenticationError()
raise ApiResponseError(e.response.status_code, str(e))
raw = resp.json()
if isinstance(raw, dict) and raw.get("errorCode") == 401:
raise AuthenticationError(raw.get("errorMessage", "EASO 认证失败"))
easo_token = (raw.get("value") or {}).get("accessToken", "")
if not easo_token:
raise ApiResponseError(0, f"EASO realm token 换取失败,响应结构异常:{raw}")
return easo_token
# ── 工厂函数 ─────────────────────────────────────────────────
def get_easo_client() -> EasoClient:
"""从当前配置创建 EasoClient,自动完成四步认证链路。
调用方(services/platform 层)无需关心 hose-access-token、UNITY JWT 或 EASO realm token 细节。
未登录时抛出 NotLoggedInError。
"""
from ekb_cli import config
corp = config.get_current_corp()
if not corp:
raise NotLoggedInError()
corp_id = config.get_current_corp_id()
access_token = corp["access_token"]
staff_id = corp["staff_id"]
hose_token = _fetch_hose_token(access_token, corp_id)
unity_jwt = _fetch_unity_jwt(access_token, corp_id, staff_id)
easo_token = _fetch_easo_realm_token(corp_id, unity_jwt, hose_token)
return EasoClient(
corp_id=corp_id,
access_token=access_token,
easo_token=easo_token,
hose_token=hose_token,
)
-156
View File
@@ -1,156 +0,0 @@
"""Piper HTTP 客户端(传输层)。
工作流配置(节点设计)子域,域名为 piper.ekuaibao.com。
认证方式与 unity.ekuaibao.com 不同:
- 使用 EASO JWT(aud=EASO,由 GET /api/engine/realm/$EASO/actions/jwt 换取)
- 需要 platformid Header(指定当前操作的自建应用 ID)
- hose-access-token Cookie
三步认证链路(均在 get_piper_client() 内自动完成):
1. accessToken → business-center.ekuaibao.com → hose-access-token
2. accessToken → app.ekuaibao.com/api/engine/realm/$EASO/actions/jwt → EASO JWT
3. EASO JWT → Authorization: Bearer → piper.ekuaibao.com 接口
调用时需传入 platform_id,因为不同自建应用的工作流接口需要对应的 platformid Header。
"""
from __future__ import annotations
import httpx
from typing import Any
from ekb_cli.errors import AuthenticationError, ApiResponseError, NotLoggedInError
PIPER_BASE_URL = "https://piper.ekuaibao.com"
_EKB_BASE_URL = "https://app.ekuaibao.com"
_BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com"
_UA = (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/147.0.0.0 Safari/537.36"
)
class PiperClient:
"""Piper 工作流配置客户端(piper.ekuaibao.com),使用 EASO JWT 认证。"""
def __init__(self, platform_id: str, easo_jwt: str, hose_token: str):
self.platform_id = platform_id
self._client = httpx.Client(
base_url=PIPER_BASE_URL,
headers={
"Authorization": f"Bearer {easo_jwt}",
"platformid": platform_id,
"Accept": "application/json, text/plain, */*",
"User-Agent": _UA,
},
cookies={"hose-access-token": hose_token},
timeout=30,
)
def _handle_error(self, e: httpx.HTTPStatusError) -> None:
if e.response.status_code == 401:
raise AuthenticationError("Piper token 已过期,请重新登录")
raise ApiResponseError(e.response.status_code, str(e))
def get(self, path: str, **params) -> Any:
try:
resp = self._client.get(path, params=params or None)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
self._handle_error(e)
data = resp.json()
if isinstance(data, dict) and data.get("errorCode") == 401:
raise AuthenticationError(data.get("errorMessage", "认证失败"))
return data
def __enter__(self):
return self
def __exit__(self, *args):
self._client.close()
def close(self):
self._client.close()
# ── 内部工具函数 ──────────────────────────────────────────────
def _fetch_hose_token(access_token: str, corp_id: str) -> str:
"""Step 1:用主站 accessToken 换取 hose-access-token(约 30 天)。"""
resp = httpx.get(
f"{_BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken",
params={"corpId": corp_id, "ekbAccessToken": access_token, "environment": "app"},
timeout=10,
)
try:
resp.raise_for_status()
except httpx.HTTPStatusError as e:
raise ApiResponseError(e.response.status_code, f"hose-access-token 换取失败: {e}")
data = resp.json()
token = data.get("data", "")
if not token:
raise ApiResponseError(0, f"hose-access-token 换取失败,响应结构异常:{data}")
return token
def _fetch_easo_jwt(access_token: str, corp_id: str, staff_id: str) -> str:
"""Step 2:换取 EASO JWT(aud=EASO,约 2 小时)。
用于 piper.ekuaibao.com 的工作流配置接口。
"""
resp = httpx.get(
f"{_EKB_BASE_URL}/api/engine/realm/$EASO/actions/jwt",
params={"corpId": corp_id},
headers={
"accesstoken": access_token,
"corpid": corp_id,
"staffid": staff_id,
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": _UA,
},
timeout=30,
)
try:
resp.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
raise AuthenticationError()
raise ApiResponseError(e.response.status_code, str(e))
raw = resp.json()
if isinstance(raw, dict) and raw.get("errorCode") == 401:
raise AuthenticationError(raw.get("errorMessage", "认证已过期,请重新执行 `ekb auth add` 更新 token"))
jwt = raw.get("id") or raw.get("value", "")
if not jwt:
raise ApiResponseError(0, f"EASO JWT 换取失败,响应结构异常:{raw}")
return jwt
# ── 工厂函数 ─────────────────────────────────────────────────
def get_piper_client(platform_id: str) -> PiperClient:
"""从当前配置创建 PiperClient,自动完成三步认证链路。
Args:
platform_id: 自建应用 ID,用于 platformid Header。
未登录时抛出 NotLoggedInError。
"""
from ekb_cli import config
corp = config.get_current_corp()
if not corp:
raise NotLoggedInError()
corp_id = config.get_current_corp_id()
access_token = corp["access_token"]
staff_id = corp["staff_id"]
hose_token = _fetch_hose_token(access_token, corp_id)
easo_jwt = _fetch_easo_jwt(access_token, corp_id, staff_id)
return PiperClient(
platform_id=platform_id,
easo_jwt=easo_jwt,
hose_token=hose_token,
)
-16
View File
@@ -1,16 +0,0 @@
"""自建应用(DataLink Platform)API 调用封装"""
from typing import List
from ekb_cli.api import EkbClient
from ekb_cli.api.platform.schemas import Platform
def list_platforms(client: EkbClient) -> List[Platform]:
"""获取企业下所有启用的自建应用。
对应接口:GET /api/v2/datalink/platform/search?scope=enable
响应结构:{"items": [...]}(非 EkbResponse 包装)
"""
raw = client.get("/v2/datalink/platform/search", scope="enable")
return [Platform.model_validate(item) for item in raw.get("items", [])]
-148
View File
@@ -1,148 +0,0 @@
"""api/platform 子域:自建应用与工作流 Pydantic 模型
包含两类模型:
- Platform:自建应用(DataLink Platform)摘要
- Workflow / WorkflowPage / WorkflowStats / WorkflowCharge:工作流(EASO Pipeline)相关模型
设计原则:
- extra="allow" 兼容快报可能新增的字段
- 该文件只存放 platform 子域专属模型;跨子域通用结构(EkbResponse / PageData)保留在父层 schemas.py
"""
from typing import Any, List, Optional
from pydantic import BaseModel, ConfigDict
# 允许字段多于定义(快报可能新增字段),已知字段必须类型正确
_cfg = ConfigDict(extra="allow")
# ── 自建应用(DataLink Platform)─────────────────────────────
class Platform(BaseModel):
"""自建应用(DataLink Platform)摘要
对应快报「应用中心 → 自建应用」列表中的每一条记录。
接口:GET /api/v2/datalink/platform/search?scope=enable
响应结构:{"items": [...]}(非 EkbResponse 包装)
"""
model_config = _cfg
id: str
name: str
nameSpell: str = ""
enName: Optional[str] = None
code: str = ""
corporationId: str
active: bool = True
type: str = "" # 固定为 DATA_LINK
groupType: str = "" # NORMAL / SPECIAL
platformType: str = "" # HAB
source: str = "" # CUSTOM_CREATE
adminIds: List[str] = []
desc: Optional[str] = None
importMethod: List[str] = []
createTime: int = 0
updateTime: int = 0
icon: Optional[Any] = None
# ── 工作流(EASO Pipeline)───────────────────────────────────
class WorkflowTask(BaseModel):
"""工作流中的单个节点(trigger / action / control)"""
model_config = _cfg
name: str = ""
type: str = "" # clock / ekuaibao-ebot-trigger / http / stop / ...
label: str = ""
desc: Optional[str] = None
groupName: str = "" # trigger / action / control
orderIndex: int = 0
status: str = "" # success / ...
class Workflow(BaseModel):
"""工作流摘要(pipelineList 中的单条)"""
model_config = _cfg
id: str
pipelineName: str = ""
state: int = 0 # 0=停用 / 1=启用
runningCount: int = 0
errorCount: int = 0
updateTime: str = ""
updateUser: Optional[str] = None
tasks: List[Any] = [] # 节点结构复杂,先用 Any 承接
desc: Optional[str] = None
customDesc: Optional[str] = None
class WorkflowPage(BaseModel):
"""工作流分页响应(EkbResponse.data)"""
model_config = _cfg
pipelineNum: int = 0 # 该应用下工作流总数
runningNum: int = 0
allRunCount: int = 0
errorCount: int = 0
number: int = 1
size: int = 20
totalPages: int = 0
totalItems: int = 0
pipelineList: List[Workflow] = []
class WorkflowStats(BaseModel):
"""工作流执行统计"""
model_config = _cfg
total: int = 0
completed: int = 0
failed: int = 0
started: int = 0
pipelineOpenCount: int = 0
pipelineCloseCount: int = 0
pipelineAllCount: int = 0
class WorkflowAlarm(BaseModel):
"""工作流告警配置"""
model_config = _cfg
alarmUser: List[Any] = []
alarmType: List[str] = []
active: bool = True
alarmScope: str = ""
class WorkflowDetail(BaseModel):
"""工作流完整配置(piper.ekuaibao.com/api/easo/pipelines/{id})
包含所有节点的完整配置,节点类型各异(trigger / action / control),
通用字段由 WorkflowTask 描述,各节点特有字段通过 extra="allow" 兜住。
"""
model_config = _cfg
id: str
label: str = "" # 工作流名称
desc: Optional[str] = None
customDesc: Optional[str] = None
state: int = 0 # 0=停用 / 1=启用
debugState: int = 0
runTimes: int = 0
errorTimes: int = 0
updateTime: str = ""
updateUser: Optional[str] = None
staffName: Optional[str] = None
version: str = ""
dataLimit: int = 20
source: int = 0
queueJobs: bool = False
tasksVersion: int = 0
tasks: List[WorkflowTask] = []
alarm: Optional[WorkflowAlarm] = None
class WorkflowCharge(BaseModel):
"""企业工作流资源包/配额"""
model_config = _cfg
corporationId: str = ""
status: str = "" # ACTIVED / ...
orderType: str = ""
total: int = 0
used: int = 0
remaining: int = 0
-66
View File
@@ -1,66 +0,0 @@
"""工作流(EASO Pipeline)API 调用封装
两个域名:
- unity.ekuaibao.com(EasoClient):工作流列表 / 统计 / 配额
- piper.ekuaibao.com(PiperClient):工作流详情(节点配置)
认证方式见各 client 模块。
响应:标准 EkbResponse 包装(code / msg / data)
"""
from ekb_cli.api.platform.easo_client import EasoClient
from ekb_cli.api.platform.piper_client import PiperClient
from ekb_cli.api.schemas import EkbResponse
from ekb_cli.api.platform.schemas import WorkflowPage, WorkflowStats, WorkflowCharge, WorkflowDetail
def list_workflows(
client: EasoClient,
platform_id: str,
page: int = 1,
page_size: int = 20,
) -> WorkflowPage:
"""分页获取指定自建应用下的工作流列表。
对应接口:GET /api/easo/pipelines/logs
参数:platformId / number(页码)/ pageSize
"""
raw = client.get(
"/api/easo/pipelines/logs",
platformId=platform_id,
number=page,
pageSize=page_size,
)
resp = EkbResponse[WorkflowPage].model_validate(raw)
return resp.data
def get_workflow_stats(client: EasoClient, platform_id: str) -> WorkflowStats:
"""获取指定自建应用的工作流执行统计(总数/成功/失败等)。
对应接口:GET /api/easo/stats
"""
raw = client.get("/api/easo/stats", platformId=platform_id)
resp = EkbResponse[WorkflowStats].model_validate(raw)
return resp.data
def get_workflow_charge(client: EasoClient) -> WorkflowCharge:
"""获取企业工作流资源包/配额信息。
对应接口:GET /api/easo/charge
"""
raw = client.get("/api/easo/charge")
resp = EkbResponse[WorkflowCharge].model_validate(raw)
return resp.data
def get_workflow(client: PiperClient, pipeline_id: str) -> WorkflowDetail:
"""获取指定工作流的完整配置(节点列表及各节点参数)。
对应接口:GET piper.ekuaibao.com/api/easo/pipelines/{pipeline_id}
认证:EASO JWT + platformid Header(由 PiperClient 持有)
"""
raw = client.get(f"/api/easo/pipelines/{pipeline_id}")
resp = EkbResponse[WorkflowDetail].model_validate(raw)
return resp.data
-40
View File
@@ -1,40 +0,0 @@
"""Rule(审核规则)相关 API 调用封装"""
from ekb_cli.api import EkbClient
from ekb_cli.api.schemas import (
EkbResponse, PageData, Rule, RuleWithAgents
)
def list_rules(client: EkbClient, page: int = 1, size: int = 1000) -> PageData[RuleWithAgents]:
raw = client.get("/engine/hab/agent/rule/list", page=page, size=size)
resp = EkbResponse[PageData[RuleWithAgents]].model_validate(raw)
return resp.data
def get_rule_detail(client: EkbClient, rule_id: str) -> Rule:
"""获取单条规则详情(比 list 多 staffId/staffName 字段)。
已逆向确认端点:GET /api/engine/hab/agent/rule/detail?id=
"""
raw = client.get("/engine/hab/agent/rule/detail", id=rule_id)
resp = EkbResponse[Rule].model_validate(raw)
return resp.data
def save_rule(client: EkbClient, payload: dict) -> Rule:
"""新建规则:payload 包含 purpose / description / level"""
raw = client.post("/engine/hab/agent/rule/save", payload)
resp = EkbResponse[Rule].model_validate(raw)
return resp.data
def update_rule(client: EkbClient, payload: dict) -> Rule:
"""更新规则:payload 包含 id / code / purpose / description / level"""
raw = client.post("/engine/hab/agent/rule/update", payload)
resp = EkbResponse[Rule].model_validate(raw)
return resp.data
def delete_rule(client: EkbClient, rule_id: str) -> None:
"""删除规则。已逆向确认端点:POST /api/engine/hab/agent/rule/delete"""
client.post("/engine/hab/agent/rule/delete", {"id": rule_id})
-185
View File
@@ -1,185 +0,0 @@
"""Pydantic 响应模型:快报 API 结构校验 + ekb-cli Server 请求/响应模型
分为两部分:
1. 快报 API 响应模型(EkbResponse / PageData / Rule / Agent 系列)
2. ekb-cli HTTP Server 的请求/响应模型(*Request / *Response / ApiResult)
约定:
- 子域专属模型放在各自的 api/<domain>/schemas.py(如 api/platform/schemas.py)
- 本文件只保留跨子域通用模型和 Server 请求/响应模型
"""
from typing import Any, Generic, List, Optional, TypeVar
from pydantic import BaseModel, ConfigDict
# 允许字段多于定义(快报可能新增字段),已知字段必须类型正确
_cfg = ConfigDict(extra="allow")
T = TypeVar("T")
# ── 快报 API:通用分页响应 ─────────────────────────────────────
class PageData(BaseModel, Generic[T]):
model_config = _cfg
number: int
size: int
totalPages: int
totalItems: int
items: List[T]
class EkbResponse(BaseModel, Generic[T]):
model_config = _cfg
code: int
msg: str = ""
data: Optional[T] = None
# ── 快报 API:Rule(审核规则)────────────────────────────────
class RuleAgentRef(BaseModel):
"""规则列表中关联的 Agent 摘要(仅 id/name/icon)"""
model_config = _cfg
id: str
name: str
icon: str = ""
class Rule(BaseModel):
model_config = _cfg
id: str
corporationId: str
code: str
version: int
purpose: str
description: str
level: str
createTime: str
updateTime: str
active: bool
staffId: str = ""
staffName: str = ""
class RuleWithAgents(Rule):
"""规则列表响应中的规则(含关联 Agent 列表)"""
agents: List[RuleAgentRef] = []
freeflows: List[Any] = []
# ── 快报 API:Agent(智能审核 Agent)─────────────────────────
class AgentRuleRef(Rule):
"""Agent 详情中内嵌的规则(完整规则字段,无 agents 字段)"""
pass
class AgentSummary(BaseModel):
"""Agent 列表中的摘要(无 agentRule 字段)"""
model_config = _cfg
id: str
corporationId: str
version: int
name: str
description: str = ""
icon: str = ""
mode: int
samplingRate: int = 0
agreeTerms: Optional[str] = None
rejectTerms: Optional[str] = None
exemptTerms: Optional[str] = None
reviewTerms: Optional[str] = None
createTime: str
updateTime: str
state: int
agentFlowRelations: List[Any] = []
class AgentDetail(AgentSummary):
"""Agent 详情(含关联规则列表)"""
agentRule: List[AgentRuleRef] = []
enrichedContext: Optional[Any] = None
# ══════════════════════════════════════════════════════════════
# ekb-cli HTTP Server 请求/响应模型
# 这些模型用于 FastAPI 路由的请求体(*Request)和响应体(*Response)
# 与快报 API 的模型分开维护,避免耦合
# ══════════════════════════════════════════════════════════════
DEFAULT_AGENT_ICON = "https://statics.ekuaibao.com/eui/eui-static/male5.png"
class ApiResult(BaseModel, Generic[T]):
"""ekb-cli Server 统一响应包装
成功时:{"success": true, "data": {...}}
失败时:{"success": false, "error": "...", "code": 404}
"""
success: bool = True
data: Optional[T] = None
error: Optional[str] = None
code: int = 0
# ── Server:Auth 请求/响应 ──────────────────────────────────
class CorpAddRequest(BaseModel):
"""添加企业认证的请求体"""
corp_id: str
name: str
access_token: str
staff_id: str
class CorpInfoResponse(BaseModel):
"""企业信息响应(不含敏感 token)"""
corp_id: str
name: str
is_current: bool
# ── Server:Agent 请求 ──────────────────────────────────────
class AgentCreateRequest(BaseModel):
"""新建 Agent 的请求体"""
name: str
description: str = ""
mode: str = "assist" # auto / semi / assist
sampling_rate: int = 0
agree_terms: str = ""
reject_terms: str = ""
exempt_terms: str = ""
review_terms: str = ""
rule_ids: List[str] = []
icon: str = DEFAULT_AGENT_ICON
class AgentUpdateRequest(BaseModel):
"""更新 Agent 的请求体(所有字段可选,只传需要改的)"""
name: Optional[str] = None
description: Optional[str] = None
mode: Optional[str] = None # auto / semi / assist
sampling_rate: Optional[int] = None
state: Optional[int] = None
agree_terms: Optional[str] = None
reject_terms: Optional[str] = None
exempt_terms: Optional[str] = None
review_terms: Optional[str] = None
# ── Server:Rule 请求 ───────────────────────────────────────
class RuleCreateRequest(BaseModel):
"""新建规则的请求体"""
purpose: str
description: str
level: str = "严重"
class RuleUpdateRequest(BaseModel):
"""更新规则的请求体(所有字段可选)"""
purpose: Optional[str] = None
description: Optional[str] = None
level: Optional[str] = None
-48
View File
@@ -1,48 +0,0 @@
# 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。
-45
View File
@@ -1,45 +0,0 @@
"""SealAI 传输层统一 re-export。
使用方(services/sealai/)只从这里导入,内部文件如何拆分对上层透明。
"""
from ekb_cli.api.sealai.client import SealAiClient
from ekb_cli.api.sealai.auth_api import get_me
from ekb_cli.api.sealai.billing_api import get_billing_status
from ekb_cli.api.sealai.rules_api import (
list_rules,
create_rule,
update_rule,
delete_rule,
list_rule_set_versions,
publish_rule_set_version,
)
from ekb_cli.api.sealai.preference_api import (
get_ai_approval_config,
save_ai_approval_config,
)
from ekb_cli.api.sealai.knowledge_api import (
list_articles,
get_article,
create_article,
patch_article,
)
__all__ = [
"SealAiClient",
"get_me",
"get_billing_status",
"list_rules",
"create_rule",
"update_rule",
"delete_rule",
"list_rule_set_versions",
"publish_rule_set_version",
"get_ai_approval_config",
"save_ai_approval_config",
"list_articles",
"get_article",
"create_article",
"patch_article",
]
-14
View File
@@ -1,14 +0,0 @@
"""SealAI 认证相关 API 封装(传输层)。
已逆向确认端点:
GET /api/v1/auth/me 当前用户及租户信息
"""
from ekb_cli.api.sealai.client import SealAiClient
from ekb_cli.api.sealai.schemas import MeData, SealAiResponse
def get_me(client: SealAiClient) -> MeData:
"""获取当前登录用户及租户信息。"""
raw = client.get("/api/v1/auth/me")
return SealAiResponse[MeData].model_validate(raw).data
-14
View File
@@ -1,14 +0,0 @@
"""SealAI 计费 / 订阅相关 API 封装(传输层)。
已逆向确认端点:
GET /api/v1/billing/status 订阅状态 + 功能配额列表
"""
from ekb_cli.api.sealai.client import SealAiClient
from ekb_cli.api.sealai.schemas import BillingStatusData, SealAiResponse
def get_billing_status(client: SealAiClient) -> BillingStatusData:
"""获取订阅状态及各功能配额使用情况。"""
raw = client.get("/api/v1/billing/status")
return SealAiResponse[BillingStatusData].model_validate(raw).data
-90
View File
@@ -1,90 +0,0 @@
"""SealAI HTTP 客户端(传输层)。
与快报主站的 EkbClient 并列,同属 api/ 传输层。
区别:SealAI 用 Bearer JWT 认证,域名按企业 corpId 动态生成。
使用方:services/sealai/auth_service 通过 _get_or_create_client() 获取实例,
并由 _sealai_call 统一管理生命周期,外部不直接持有或关闭此对象。
"""
from __future__ import annotations
import httpx
from typing import Any
from ekb_cli.errors import AuthenticationError, ApiResponseError
class SealAiClient:
"""SealAI REST 客户端,所有请求携带 Authorization: Bearer {token}。"""
def __init__(self, corp_id: str, bearer_token: str):
self.corp_id = corp_id
self._base_url = f"https://{corp_id.lower()}.sealai.cc"
self._client = httpx.Client(
base_url=self._base_url,
headers={
"Authorization": f"Bearer {bearer_token}",
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/146.0.0.0 Safari/537.36"
),
},
timeout=30,
)
def _handle_error(self, e: httpx.HTTPStatusError) -> None:
if e.response.status_code == 401:
raise AuthenticationError("SealAI token 已过期,请重新登录")
raise ApiResponseError(e.response.status_code, str(e))
def get(self, path: str, params: dict | None = None, **kwargs) -> Any:
try:
merged = {**(params or {}), **kwargs} or None
resp = self._client.get(path, params=merged)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
self._handle_error(e)
return resp.json()
def post(self, path: str, body: dict | None = None, **params) -> Any:
try:
resp = self._client.post(path, json=body or {}, params=params or None)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
self._handle_error(e)
return resp.json()
def put(self, path: str, body: dict | None = None) -> Any:
try:
resp = self._client.put(path, json=body or {})
resp.raise_for_status()
except httpx.HTTPStatusError as e:
self._handle_error(e)
return resp.json()
def patch(self, path: str, body: dict | None = None) -> Any:
try:
resp = self._client.patch(path, json=body or {})
resp.raise_for_status()
except httpx.HTTPStatusError as e:
self._handle_error(e)
return resp.json()
def delete(self, path: str) -> None:
try:
resp = self._client.delete(path)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
self._handle_error(e)
def __enter__(self):
return self
def __exit__(self, *args):
self._client.close()
def close(self):
self._client.close()
-132
View File
@@ -1,132 +0,0 @@
"""SealAI 知识文档 API 封装(传输层)。
已逆向确认端点:
GET /api/v1/knowledge/articles 文档列表(场景过滤 + 分页 + 排序)
POST /api/v1/knowledge/articles 新建文档
GET /api/v1/knowledge/articles/{id} 文档详情
PATCH /api/v1/knowledge/articles/{id} 更新文档(请求体为 {attributes: {...}})
注意:PATCH 请求体有特殊包装:{"attributes": {改动字段}},与 POST 直接传字段不同。
"""
from typing import Optional
from ekb_cli.api.sealai.client import SealAiClient
from ekb_cli.api.sealai.schemas import (
SealAiResponse,
KnowledgeArticle,
KnowledgeArticleListData,
)
def list_articles(
client: SealAiClient,
*,
scenarios: Optional[list[str]] = None,
offset: int = 0,
limit: int = 20,
sort_by: str = "createdAt",
sort_order: str = "desc",
) -> KnowledgeArticleListData:
"""获取知识文档列表。
Args:
scenarios: 场景过滤,如 ["audit"]、["fill"],None 表示不过滤
offset: 分页偏移量(默认 0)
limit: 每页数量(默认 20)
sort_by: 排序字段(默认 createdAt)
sort_order: 排序方向,"asc" | "desc"(默认 desc)
"""
# 构造 filter[scenarios][N]=xxx 风格的 query 参数
params: dict = {
"offset": offset,
"limit": limit,
"sortBy": sort_by,
"sortOrder": sort_order,
}
if scenarios:
for i, s in enumerate(scenarios):
params[f"filter[scenarios][{i}]"] = s
raw = client.get("/api/v1/knowledge/articles", params=params)
return SealAiResponse[KnowledgeArticleListData].model_validate(raw).data
def get_article(client: SealAiClient, article_id: str) -> KnowledgeArticle:
"""获取单篇知识文档详情。"""
raw = client.get(f"/api/v1/knowledge/articles/{article_id}")
return SealAiResponse[KnowledgeArticle].model_validate(raw).data
def create_article(
client: SealAiClient,
*,
title: str,
purpose: str,
content: str,
content_type: str = "policy",
status: str = "published",
scenarios: Optional[list[str]] = None,
tags: Optional[list[str]] = None,
) -> KnowledgeArticle:
"""新建知识文档。
Args:
title: 文档标题
purpose: 适用说明
content: 正文内容(Markdown 格式)
content_type: 内容类型,默认 "policy"
status: "published" | "draft",默认 "published"
scenarios: 适用场景列表,如 ["audit", "fill"]
tags: 标签列表,"__all__" 表示全适用
"""
body = {
"title": title,
"purpose": purpose,
"contentType": content_type,
"content": content,
"status": status,
"scenarios": scenarios or [],
"tags": tags or [],
}
raw = client.post("/api/v1/knowledge/articles", body)
return SealAiResponse[KnowledgeArticle].model_validate(raw).data
def patch_article(
client: SealAiClient,
article_id: str,
*,
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,
) -> KnowledgeArticle:
"""更新知识文档(Patch 式,只传改动字段)。
注意:PATCH 请求体格式为 {"attributes": {改动字段}},
与 POST 的直传字段格式不同,这里已在传输层做好封装。
"""
attributes: dict = {}
if title is not None:
attributes["title"] = title
if purpose is not None:
attributes["purpose"] = purpose
if content is not None:
attributes["content"] = content
if content_type is not None:
attributes["contentType"] = content_type
if status is not None:
attributes["status"] = status
if enabled is not None:
attributes["enabled"] = enabled
if scenarios is not None:
attributes["scenarios"] = scenarios
if tags is not None:
attributes["tags"] = tags
raw = client.patch(f"/api/v1/knowledge/articles/{article_id}", {"attributes": attributes})
return SealAiResponse[KnowledgeArticle].model_validate(raw).data
-41
View File
@@ -1,41 +0,0 @@
"""SealAI 风格偏好 API 封装(传输层)。
已逆向确认端点:
GET /api/v1/agent/ai-approval/config 获取 AI 审批配置(决策偏好 + 集成信息)
POST /api/v1/agent/ai-approval/config 保存 AI 审批配置(整体替换)
注意:POST 是整体替换语义,需将完整配置对象回传,
调用方(services 层)负责先 GET 再 merge,再 POST。
"""
from ekb_cli.api.sealai.client import SealAiClient
from ekb_cli.api.sealai.schemas import (
SealAiResponse,
AiApprovalConfig,
AiApprovalSaveResult,
)
def get_ai_approval_config(client: SealAiClient) -> AiApprovalConfig:
"""获取 AI 审批配置(风格偏好 + 集成系统信息)。"""
raw = client.get("/api/v1/agent/ai-approval/config")
return SealAiResponse[AiApprovalConfig].model_validate(raw).data
def save_ai_approval_config(
client: SealAiClient,
config: AiApprovalConfig,
) -> AiApprovalSaveResult:
"""保存 AI 审批配置(整体替换)。
Args:
config: 完整的配置对象,需包含 decisionPreferences、
integrationSystem、integrations 等所有字段。
Returns:
AiApprovalSaveResult,含 success 标志。
"""
raw = client.post(
"/api/v1/agent/ai-approval/config",
config.model_dump(exclude_none=False),
)
return SealAiResponse[AiApprovalSaveResult].model_validate(raw).data
-90
View File
@@ -1,90 +0,0 @@
"""SealAI 审核规则 API 封装(传输层)。
已逆向确认端点:
GET /api/v1/rules 草稿规则列表
POST /api/v1/rules 新建草稿规则
PUT /api/v1/rules/{id} 更新草稿规则(partial,只传改动字段)
DELETE /api/v1/rules/{id} 删除草稿规则
GET /api/v1/rule-set-versions 已发布版本历史列表
POST /api/v1/rule-set-versions/publish 发布当前草稿为新版本
"""
from ekb_cli.api.sealai.client import SealAiClient
from ekb_cli.api.sealai.schemas import (
SealAiResponse,
DraftRule,
DraftRulesData,
RuleSetVersion,
PublishVersionData,
)
def list_rules(client: SealAiClient) -> DraftRulesData:
"""获取草稿区所有审核规则。"""
raw = client.get("/api/v1/rules")
return SealAiResponse[DraftRulesData].model_validate(raw).data
def create_rule(
client: SealAiClient,
description: str,
scope: str,
strictness: str,
) -> DraftRule:
"""新建草稿审核规则。
Args:
description: 规则描述
scope: 适用场景(费用类型等自由文本)
strictness: MUST_FOLLOW | SHOULD_FOLLOW | SUGGESTION
"""
raw = client.post("/api/v1/rules", {
"description": description,
"scope": scope,
"strictness": strictness,
})
return SealAiResponse[DraftRule].model_validate(raw).data
def update_rule(
client: SealAiClient,
rule_id: str,
*,
description: str | None = None,
scope: str | None = None,
strictness: str | None = None,
) -> DraftRule:
"""更新草稿规则(partial,只传改动字段)。"""
body = {}
if description is not None:
body["description"] = description
if scope is not None:
body["scope"] = scope
if strictness is not None:
body["strictness"] = strictness
raw = client.put(f"/api/v1/rules/{rule_id}", body)
return SealAiResponse[DraftRule].model_validate(raw).data
def delete_rule(client: SealAiClient, rule_id: str) -> None:
"""删除草稿规则。"""
client.delete(f"/api/v1/rules/{rule_id}")
def list_rule_set_versions(client: SealAiClient) -> list[RuleSetVersion]:
"""获取已发布的规则集版本历史(倒序,最新在前)。"""
raw = client.get("/api/v1/rule-set-versions")
return SealAiResponse[list[RuleSetVersion]].model_validate(raw).data
def publish_rule_set_version(
client: SealAiClient,
version_name: str,
) -> PublishVersionData:
"""将当前草稿区规则发布为新版本。
Args:
version_name: 版本名称(如 "审核规则 版本5")
"""
raw = client.post("/api/v1/rule-set-versions/publish", {"versionName": version_name})
return SealAiResponse[PublishVersionData].model_validate(raw).data
-351
View File
@@ -1,351 +0,0 @@
"""SealAI 平台的 Pydantic 响应模型。
SealAI({corpId}.sealai.cc)是独立于快报主站的 Next.js 平台,
认证使用 Bearer JWT,数据结构与快报 HAB 模块完全独立。
"""
from __future__ import annotations
from typing import Generic, Optional, TypeVar
from pydantic import BaseModel
T = TypeVar("T")
# ── 通用包装 ──────────────────────────────────────────────────────────────────
class SealAiResponse(BaseModel, Generic[T]):
"""SealAI API 统一响应包装:{ data: T }"""
data: T
class Config:
extra = "allow"
# ── 认证 ──────────────────────────────────────────────────────────────────────
class HosecloudStaff(BaseModel):
staffId: str
name: str
code: str = ""
bindTime: int
class Config:
extra = "allow"
class SealAiUser(BaseModel):
id: str
tenantId: str
name: str
isAdmin: bool
permissions: list[str]
providerUserId: str # 对应快报 staffId
hosecloudStaff: Optional[HosecloudStaff] = None
class Config:
extra = "allow"
class HoseCorpConfig(BaseModel):
apiKey: str
corporationId: str
corporationName: str
class Config:
extra = "allow"
class SealAiTenant(BaseModel):
id: str
name: str
tenantSlug: str # corpId 小写
isDemo: bool
logoUrl: Optional[str] = None
hoseCorpConfig: HoseCorpConfig
class Config:
extra = "allow"
class MeData(BaseModel):
user: SealAiUser
tenant: SealAiTenant
class Config:
extra = "allow"
# ── 计费 ──────────────────────────────────────────────────────────────────────
class Subscription(BaseModel):
id: str
tenantId: str
planId: str
status: str # "active" | "expired"
startDate: str
createdAt: str
updatedAt: str
class Config:
extra = "allow"
class Feature(BaseModel):
"""订阅功能项,三种形态:开关型 / 配额型 / 余额型"""
code: str
name: str
# 开关型
enabled: Optional[bool] = None
# 配额型
quota: Optional[int] = None
used: Optional[int] = None
remaining: Optional[int] = None
# 余额型
balance: Optional[int] = None
totalQuota: Optional[int] = None
totalUsed: Optional[int] = None
nextResetDate: Optional[str] = None
class Config:
extra = "allow"
class BillingStatusData(BaseModel):
subscriptions: list[Subscription]
features: list[Feature]
class Config:
extra = "allow"
def get_feature(self, code: str) -> Optional[Feature]:
for f in self.features:
if f.code == code:
return f
return None
# ── 审核规则草稿 ──────────────────────────────────────────────────────────────
class DraftRule(BaseModel):
"""草稿区单条审核规则。"""
id: str
tenantId: str
description: str # 规则描述
scope: str # 适用场景(费用类型等)
strictness: str # MUST_FOLLOW / SHOULD_FOLLOW / SUGGESTION
status: str # DRAFT
createdAt: int
updatedAt: int
class Config:
extra = "allow"
class DraftRulesData(BaseModel):
"""GET /api/v1/rules 响应体 data 字段。"""
rules: list[DraftRule]
hasPendingDeletes: bool = False
class Config:
extra = "allow"
# ── 已发布版本 ────────────────────────────────────────────────────────────────
class PublishedRuleSnapshot(BaseModel):
"""版本快照内单条规则(无 id,不可变)。"""
description: str
scope: str
strictness: str
class Config:
extra = "allow"
class RuleSetVersion(BaseModel):
"""已发布的规则集版本快照。"""
id: str
tenantId: str
versionNumber: int
versionName: str
publishedBy: str
publishedByName: str
rules: list[PublishedRuleSnapshot]
publishedAt: int
createdAt: int
class Config:
extra = "allow"
class PublishVersionData(BaseModel):
"""POST /api/v1/rule-set-versions/publish 响应体 data 字段。"""
version: RuleSetVersion
rulesCount: int
class Config:
extra = "allow"
# ── 风格偏好(AI 审批配置) ───────────────────────────────────────────────────
class DecisionPreferences(BaseModel):
"""AI 审批四类决策场景的提示词配置。
Attributes:
explicitApprove: 明确通过的条件描述
explicitReject: 明确拒绝的条件描述
exemptApprove: 豁免通过的条件描述
review: 转人工判断的条件描述
"""
explicitApprove: str
explicitReject: str
exemptApprove: str
review: str
class Config:
extra = "allow"
class AiApprovalIntegration(BaseModel):
"""单个集成系统配置(快报 / 飞书 / 钉钉等)。"""
type: str # "hosecloud" 等
mode: Optional[str] = None # "fully_automatic" | "semi_automatic"
autoApprovalRate: Optional[int] = None
class Config:
extra = "allow"
class AiApprovalConfig(BaseModel):
"""GET/POST /api/v1/agent/ai-approval/config 响应体 data 字段。
风格偏好页面的完整配置,包含决策偏好和集成系统信息。
写入时需原样回传整个对象(整体替换语义)。
"""
decisionPreferences: DecisionPreferences
integrationSystem: Optional[str] = None # "feishu" | "dingtalk" 等
integrations: Optional[list[AiApprovalIntegration]] = None
class Config:
extra = "allow"
class AiApprovalSaveResult(BaseModel):
"""POST /api/v1/agent/ai-approval/config 响应体 data 字段。"""
success: bool
class Config:
extra = "allow"
# ── 知识文档 ──────────────────────────────────────────────────────────────────
class KnowledgeArticle(BaseModel):
"""知识文档条目(新建/详情/列表元素)。
Attributes:
id: 文档唯一 ID
tenantId: 租户 ID
title: 文档标题
purpose: 适用说明(适用场景文字描述)
contentType: 内容类型,如 "policy"
content: 正文内容(Markdown 格式)
status: "published" | "draft"
enabled: 是否启用
scenarios: 适用场景列表,如 ["audit", "fill"]
tags: 标签列表,"__all__" 表示全适用
category: 分类(可为 null)
categoryTags: 分类标签列表
createdBy: 创建人 ID
createdByName: 创建人姓名
createdAt: 创建时间(毫秒时间戳)
updatedAt: 更新时间(毫秒时间戳)
updatedBy: 最后更新人 ID
updatedByName: 最后更新人姓名
isDeleted: 是否已删除
"""
id: str
tenantId: str
title: str
purpose: str
contentType: str # "policy" 等
content: str # Markdown 正文
status: str # "published" | "draft"
enabled: bool = True
scenarios: list[str] = [] # ["audit", "fill"] 等
tags: list[str] = [] # ["__all__"] 或具体标签
category: Optional[str] = None
categoryTags: list[str] = []
createdBy: Optional[str] = None
createdByName: Optional[str] = None
createdAt: Optional[int] = None
updatedAt: Optional[int] = None
updatedBy: Optional[str] = None
updatedByName: Optional[str] = None
isDeleted: bool = False
class Config:
extra = "allow"
class KnowledgeArticleListData(BaseModel):
"""GET /api/v1/knowledge/articles 响应体 data 字段。"""
articles: list[KnowledgeArticle]
total: Optional[int] = None
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
-35
View File
@@ -1,35 +0,0 @@
# 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` 命令全图和接口对照表
View File
Whitespace-only changes.
@@ -1,43 +0,0 @@
# ekb agent 命令说明
## 枚举常量
**mode(审核模式)**
| 值 | 含义 | 备注 |
|---|---|---|
| `0` | 全自动 | 无 samplingRate |
| `1` | 半自动 | samplingRate 0–100,表示抽检比例 |
| `2` | 辅助 | |
**state(Agent 状态)**
| 值 | 含义 | 备注 |
|---|---|---|
| `0` | 草稿 | 新建默认值,未发布 |
| `1` | 已发布 | 已关联审批流并生效 |
| `2` | 已删除 | 不可恢复 |
## 四类条款语义(对应前端「AI审核决策偏好」)
| 字段 | 前端标签 | AI 行为 |
|---|---|---|
| `agreeTerms` | 明确同意 | 满足 → 直接**通过** |
| `rejectTerms` | 明确驳回 | 满足 → 直接**拒绝** |
| `exemptTerms` | 理应驳回,但可豁免(即备注同意) | 满足 → **豁免**,备注同意 |
| `reviewTerms` | 建议复核,转人工 | 无法判断 → **转人工**处理 |
## 命令速查
```bash
ekb agent list # 列出所有 Agent
ekb agent get <id> # 查看 Agent 详情(含关联规则)
ekb agent get <id> --full # 不截断规则字段
ekb agent create --name <名称> --help # 新建 Agent,查看全部参数
ekb agent copy <id> # 复制 Agent(名称自动加「副本」)
ekb agent update <id> --help # 查看可修改字段
ekb agent update <id> --mode assist # 切换模式(auto/semi/assist)
ekb agent delete <id> # 删除 Agent(方向键交互确认)
ekb agent delete <id> --ai # 删除 Agent(y/N 文字确认,AI/脚本友好)
ekb agent delete <id> --yes # 删除 Agent(跳过确认,危险)
```
-38
View File
@@ -1,38 +0,0 @@
# ekb agent rule 命令说明
## 枚举常量
**level(风险等级)**
| 值 | 含义 | 显示颜色 |
|---|---|---|
| `"严重"` | 高风险 | 红色 |
| `"一般"` | 普通风险 | 黄色 |
## 关联关系
- 规则与 Agent 是多对多关系:一条规则可关联多个 Agent,一个 Agent 可关联多条规则
- `rule/list` 响应中每条规则的 `agents[]` 字段列出当前关联的 Agent(id + name)
- `agent/detail` 响应中的 `agentRule[]` 字段列出当前 Agent 关联的规则
## 命令速查
```bash
ekb agent rules # 列出所有规则(截断版)
ekb agent rules --full # 列出所有规则(完整版)
ekb agent rules --level 严重 # 筛选严重等级
ekb agent rule-get <编码或ID> # 查看规则详情(含关联 Agent 列表)
# 编码支持多种写法:0001 / 01 / 1 / #0001(自动补零对齐)
ekb agent rule-create --purpose <场景> --desc <描述> --level 严重
# --level 默认严重,可选:严重 / 一般
```
## 已知 API
```
GET /api/engine/hab/agent/rule/list # 拉取全部规则,支持 page/size
POST /api/engine/hab/agent/rule/save # 新建规则,body: {purpose, description, level}
POST /api/engine/hab/agent/rule/update # 更新规则,body: {id, code, purpose, description, level}
```
-27
View File
@@ -1,27 +0,0 @@
"""agent 子命令组"""
import typer
from ekb_cli.commands.agent.list import cmd_list
from ekb_cli.commands.agent.detail import cmd_detail
from ekb_cli.commands.agent.logs import cmd_logs
from ekb_cli.commands.agent.update import cmd_update
from ekb_cli.commands.agent.create import cmd_create
from ekb_cli.commands.agent.copy import cmd_copy
from ekb_cli.commands.agent.rule_list import cmd_rule_list
from ekb_cli.commands.agent.rule_detail import cmd_rule_detail
from ekb_cli.commands.agent.rule_create import cmd_rule_create
from ekb_cli.commands.agent.delete import cmd_delete
app = typer.Typer(help="智能审核 Agent 管理")
app.command("list")(cmd_list)
app.command("get")(cmd_detail)
app.command("create")(cmd_create)
app.command("copy")(cmd_copy)
app.command("update")(cmd_update)
app.command("delete")(cmd_delete)
app.command("logs")(cmd_logs)
app.command("rules")(cmd_rule_list)
app.command("rule-get")(cmd_rule_detail)
app.command("rule-create")(cmd_rule_create)
-23
View File
@@ -1,23 +0,0 @@
"""ekb agent copy <id>:复制智能审核 Agent(表现层)
不导入 api 层;通过 services.copy_agent_cmd 复制 Agent。
EkbError 由 CLI 入口全局 handler 统一处理,本层不 catch。
"""
import typer
from rich import print as rprint
from ekb_cli.services import copy_agent_cmd, MODE_DISPLAY
def cmd_copy(
agent_id: str = typer.Argument(..., help="要复制的 Agent ID"),
):
"""复制 Agent(新 Agent 名称为原名称加「(副本)」)"""
src, new = copy_agent_cmd(agent_id)
rprint("[green]✓ Agent 复制成功[/green]")
rprint(f" 原 Agent:[dim]{src.name}[/dim] → 新 Agent:[bold]{new.name}[/bold]")
rprint(f" 新 ID:[dim]{new.id}[/dim]")
rprint(f" 模式:{MODE_DISPLAY.get(new.mode, str(new.mode))}")
rprint(f" 关联规则数:{len(new.agentRule)}")
-47
View File
@@ -1,47 +0,0 @@
"""ekb agent create:新建智能审核 Agent(表现层)
不导入 api 层;通过 services.create_agent_cmd 创建 Agent。
EkbError 由 CLI 入口全局 handler 统一处理,本层不 catch。
"""
from typing import Optional, List
import typer
from rich import print as rprint
from ekb_cli.services import create_agent_cmd, AgentCreateInput, MODE_DISPLAY
def cmd_create(
name: str = typer.Option(..., "--name", "-n", help="Agent 名称(唯一)"),
description: str = typer.Option("", "--description", "-d", help="描述"),
mode: str = typer.Option("assist", "--mode", "-m", help="模式:auto / semi / assist"),
agree_terms: str = typer.Option("", "--agree-terms", help="明确同意条款"),
reject_terms: str = typer.Option("", "--reject-terms", help="明确驳回条款"),
exempt_terms: str = typer.Option("", "--exempt-terms", help="豁免(备注同意)条款"),
review_terms: str = typer.Option("", "--review-terms", help="转人工条款"),
rule_ids: Optional[List[str]] = typer.Option(None, "--rule-id", "-r", help="关联规则 ID(可多次传入)"),
icon: str = typer.Option("", "--icon", help="头像 URL(留空使用默认)"),
):
"""新建智能审核 Agent"""
from ekb_cli.services.agent_service import DEFAULT_ICON
inp = AgentCreateInput(
name=name,
description=description,
mode=mode,
agree_terms=agree_terms,
reject_terms=reject_terms,
exempt_terms=exempt_terms,
review_terms=review_terms,
rule_ids=rule_ids or [],
icon=icon or DEFAULT_ICON,
)
data = create_agent_cmd(inp)
rprint("[green]✓ Agent 创建成功[/green]")
rprint(f" ID:[dim]{data.id}[/dim]")
rprint(f" 名称:[bold]{data.name}[/bold]")
rprint(f" 模式:{MODE_DISPLAY.get(data.mode, str(data.mode))}")
rprint(f" 关联规则数:{len(data.agentRule)}")
rprint(f" 创建时间:[dim]{data.createTime}[/dim]")
-76
View File
@@ -1,76 +0,0 @@
"""ekb agent delete <id>:删除智能审核 Agent(表现层)
确认逻辑:
- 默认:终端可用时用方向键菜单(questionary),否则降级为文字输入
- --ai:强制文字输入模式(适合 AI/脚本非交互式环境)
- --yes:跳过确认直接删除
不导入 api 层;通过 services.get_agent_cmd / delete_agent_cmd 操作。
EkbError 由 CLI 入口全局 handler 统一处理,本层不 catch。
"""
import sys
import questionary
import typer
from rich import print as rprint
from rich.panel import Panel
from rich.console import Console
from ekb_cli.services import get_agent_cmd, delete_agent_cmd
console = Console()
_CANCEL = "取消(默认安全)"
_CONFIRM = "确认删除"
def cmd_delete(
agent_id: str = typer.Argument(..., help="要删除的 Agent ID"),
yes: bool = typer.Option(False, "--yes", "-y", help="跳过确认直接删除(危险)"),
ai: bool = typer.Option(False, "--ai", help="AI/脚本模式:改用文字输入 y/N 确认"),
):
"""删除 Agent(不可恢复,操作前会展示 Agent 信息并要求确认)"""
# 先拉详情用于展示(service 层已处理 NotFoundError)
d = get_agent_cmd(agent_id)
rule_count = len(d.agentRule)
console.print(Panel(
"\n".join([
f"[bold]名称[/bold] {d.name}",
f"[bold]ID[/bold] [dim]{d.id}[/dim]",
f"[bold]描述[/bold] {d.description or '(无)'}",
f"[bold]关联规则[/bold] {rule_count} 条{'(规则本身不会被删除)' if rule_count else ''}",
f"[bold]更新时间[/bold] {d.updateTime}",
]),
title="[bold red]⚠ 即将删除以下 Agent[/bold red]",
border_style="red",
expand=False,
))
if not yes:
if ai or not sys.stdin.isatty():
rprint(f"确认删除 Agent「{d.name}」?输入 y 确认,其他任意键取消:", end=" ")
answer = input().strip().lower()
if answer != "y":
rprint("[dim]已取消[/dim]")
raise typer.Exit(0)
else:
choice = questionary.select(
f"确认删除 Agent「{d.name}」?",
choices=[_CANCEL, _CONFIRM],
default=_CANCEL,
style=questionary.Style([
("selected", "fg:#ff5555 bold"),
("pointer", "fg:#ff5555 bold"),
("highlighted", "fg:#ff5555"),
("question", "bold"),
]),
).ask()
if choice != _CONFIRM:
rprint("[dim]已取消[/dim]")
raise typer.Exit(0)
# 确认后执行删除
delete_agent_cmd(agent_id)
rprint(f"[green]✓ Agent「{d.name}」已删除[/green]")
-87
View File
@@ -1,87 +0,0 @@
"""ekb agent get <id>:查看 Agent 详情(表现层)
不导入 api 层;通过 services.get_agent_cmd 获取数据。
"""
import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich import print as rprint
from ekb_cli.services import get_agent_cmd
console = Console()
STATE_MAP = {0: "[dim]草稿[/dim]", 1: "[green]已发布[/green]"}
MODE_MAP = {0: "全自动", 1: "半自动", 2: "辅助"}
DESC_MAX = 24
PURPOSE_MAX = 16
def cmd_detail(
agent_id: str = typer.Argument(..., help="Agent ID"),
full: bool = typer.Option(False, "--full", "-f", help="显示完整内容,不截断规则字段"),
):
"""查看 Agent 详情"""
d = get_agent_cmd(agent_id)
state = STATE_MAP.get(d.state, str(d.state))
mode = MODE_MAP.get(d.mode, str(d.mode))
if d.mode == 1:
mode += f"(抽检 {d.samplingRate}%)"
content = "\n".join([
f"[bold]ID[/bold] {d.id}",
f"[bold]名称[/bold] {d.name}",
f"[bold]状态[/bold] {state}",
f"[bold]模式[/bold] {mode}",
f"[bold]描述[/bold] {d.description or '(无)'}",
f"[bold]创建时间[/bold] {d.createTime}",
f"[bold]更新时间[/bold] {d.updateTime}",
"",
f"[bold cyan]明确同意[/bold cyan]\n{d.agreeTerms}",
"",
f"[bold red]明确驳回[/bold red]\n{d.rejectTerms}",
"",
f"[bold yellow]理应驳回,但可豁免(即备注同意)[/bold yellow]\n{d.exemptTerms}",
"",
f"[bold green]建议复核,转人工[/bold green]\n{d.reviewTerms}",
])
console.print(Panel(content, title=f"[bold]{d.name}[/bold]", expand=False))
if d.agentRule:
table = Table(title="关联规则", show_lines=True)
if full:
table.add_column("规则描述")
table.add_column("规则编码", style="dim", no_wrap=True)
table.add_column("适用场景")
table.add_column("风险等级", no_wrap=True)
table.add_column("更新日期", style="dim", no_wrap=True)
table.add_column("ID", style="dim", no_wrap=True)
else:
table.add_column("规则描述", max_width=DESC_MAX, no_wrap=True)
table.add_column("规则编码", style="dim", no_wrap=True)
table.add_column("适用场景", max_width=PURPOSE_MAX, no_wrap=True)
table.add_column("风险等级", no_wrap=True)
table.add_column("更新日期", style="dim", no_wrap=True)
table.add_column("ID", style="dim", no_wrap=True)
any_truncated = False
total_chars = 0
for r in d.agentRule:
level_str = f"[red]{r.level}[/red]" if r.level == "严重" else f"[yellow]{r.level}[/yellow]"
update_date = r.updateTime[:10]
total_chars += len(r.description) + len(r.purpose)
if not full and (len(r.description) > DESC_MAX or len(r.purpose) > PURPOSE_MAX):
any_truncated = True
table.add_row(r.description, r.code, r.purpose, level_str, update_date, r.id)
console.print(table)
if any_truncated:
rprint(f"[yellow]⚠ 部分规则字段已截断,完整规则文本共 {total_chars} 字符[/yellow]")
rprint("[dim]使用 --full 参数获取完整内容:ekb agent get <id> --full[/dim]")
else:
rprint("[dim](未关联任何规则)[/dim]")
-38
View File
@@ -1,38 +0,0 @@
"""ekb agent list:列出所有智能审核 Agent(表现层)"""
import typer
from rich.console import Console
from rich.table import Table
from rich import print as rprint
from ekb_cli.services import list_agents_cmd
console = Console()
STATE_MAP = {0: "[dim]草稿[/dim]", 1: "[green]已发布[/green]"}
MODE_MAP = {0: "全自动", 1: "半自动", 2: "辅助"}
def cmd_list():
"""列出所有智能审核 Agent"""
page = list_agents_cmd()
if not page.items:
rprint("[yellow]暂无 Agent[/yellow]")
raise typer.Exit()
table = Table(title="智能审核 Agent 列表")
table.add_column("ID", style="dim")
table.add_column("名称")
table.add_column("模式")
table.add_column("状态")
table.add_column("更新时间")
for item in page.items:
table.add_row(
item.id,
item.name,
MODE_MAP.get(item.mode, str(item.mode)),
STATE_MAP.get(item.state, str(item.state)),
item.updateTime,
)
console.print(table)
-8
View File
@@ -1,8 +0,0 @@
"""ekb agent logs <id>:查看 Agent 审核日志(待实现)"""
from rich import print as rprint
def cmd_logs(agent_id: str):
"""查看 Agent 审核日志"""
rprint(f"[yellow]待实现:agent logs {agent_id}[/yellow]")
-28
View File
@@ -1,28 +0,0 @@
"""ekb agent rule-create:新建审核规则(表现层)
不导入 api 层;通过 services.create_rule_cmd 新建规则。
EkbError 由 CLI 入口全局 handler 统一处理,本层不 catch。
"""
import typer
from rich import print as rprint
from ekb_cli.services import create_rule_cmd
def cmd_rule_create(
purpose: str = typer.Option(..., "--purpose", "-p", help="适用场景(规则名称)"),
description: str = typer.Option(..., "--desc", "-d", help="规则描述"),
level: str = typer.Option("严重", "--level", "-l", help="风险等级:严重 / 一般"),
):
"""新建审核规则"""
rule = create_rule_cmd(purpose=purpose, description=description, level=level)
rprint("[green]✓ 规则创建成功[/green]")
rprint(f" 编码:[bold]{rule.code}[/bold]")
rprint(f" ID:[dim]{rule.id}[/dim]")
rprint(f" 适用场景:{rule.purpose}")
rprint(f" 描述:{rule.description}")
level_tag = "red" if rule.level == "严重" else "yellow"
rprint(f" 风险等级:[{level_tag}]{rule.level}[/{level_tag}]")
rprint(f" 创建时间:[dim]{rule.createTime}[/dim]")
-48
View File
@@ -1,48 +0,0 @@
"""ekb agent rule-get:查看单条规则详情(表现层)
不导入 api 层;通过 services.get_rule_cmd 获取数据。
EkbError 由 CLI 入口全局 handler 统一处理,本层不 catch。
"""
import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich import print as rprint
from ekb_cli.services import get_rule_cmd
console = Console()
def cmd_rule_detail(
rule_ref: str = typer.Argument(..., help="规则 ID 或编码(如 2040826... 或 #0001 或 0001)"),
):
"""查看单条规则详情(含关联 Agent 列表)"""
rule = get_rule_cmd(rule_ref)
level_color = "red" if rule.level == "严重" else "yellow"
level_str = f"[bold {level_color}]{rule.level}[/bold {level_color}]"
meta = Table(box=None, show_header=False, padding=(0, 1))
meta.add_column(style="dim", justify="right")
meta.add_column()
meta.add_row("编码", f"[cyan bold]{rule.code}[/cyan bold]")
meta.add_row("风险等级", level_str)
meta.add_row("ID", f"[dim]{rule.id}[/dim]")
meta.add_row("创建时间", f"[dim]{rule.createTime}[/dim]")
meta.add_row("更新时间", f"[dim]{rule.updateTime}[/dim]")
console.print(Panel(meta, title=f"[bold {level_color}]{rule.code}[/bold {level_color}]", expand=False))
console.print(Panel(rule.purpose or "(无)", title="[bold cyan]适用场景[/bold cyan]", expand=False))
console.print(Panel(rule.description or "(无)", title="[bold cyan]规则描述[/bold cyan]", expand=False))
if rule.agents:
table = Table(title=f"关联 Agent(共 {len(rule.agents)} 个)", show_lines=True)
table.add_column("名称")
table.add_column("ID", style="dim", no_wrap=True)
for a in rule.agents:
table.add_row(a.name, a.id)
console.print(table)
else:
rprint("[dim](未关联任何 Agent)[/dim]")
-71
View File
@@ -1,71 +0,0 @@
"""ekb agent rules:列出企业所有审核规则(表现层)
不导入 api 层;通过 services.list_rules_cmd 获取数据。
EkbError 由 CLI 入口全局 handler 统一处理,本层不 catch。
"""
import typer
from rich.console import Console
from rich.table import Table
from rich import print as rprint
from ekb_cli.services import list_rules_cmd
console = Console()
DESC_MAX = 20
PURPOSE_MAX = 12
def cmd_rule_list(
full: bool = typer.Option(False, "--full", "-f", help="显示完整内容,不截断描述字段"),
level: str = typer.Option(None, "--level", "-l", help="按风险等级筛选:严重 / 一般"),
):
"""列出企业所有审核规则"""
page, items = list_rules_cmd(level=level)
if not items:
rprint("[dim](暂无规则)[/dim]")
return
title = (
f"审核规则(共 {page.totalItems} 条,筛选:{level})"
if level else
f"审核规则(共 {page.totalItems} 条)"
)
table = Table(title=title, show_lines=True)
table.add_column("规则编码", style="dim", no_wrap=True)
if full:
table.add_column("规则描述")
table.add_column("适用场景")
else:
table.add_column("规则描述", max_width=DESC_MAX, no_wrap=True)
table.add_column("适用场景", max_width=PURPOSE_MAX, no_wrap=True)
table.add_column("风险等级", no_wrap=True)
table.add_column("关联Agent", no_wrap=True)
table.add_column("更新日期", style="dim", no_wrap=True)
table.add_column("ID", style="dim", no_wrap=True)
any_truncated = False
total_chars = 0
for r in items:
level_str = f"[red]{r.level}[/red]" if r.level == "严重" else f"[yellow]{r.level}[/yellow]"
update_date = r.updateTime[:10]
total_chars += len(r.description) + len(r.purpose)
if not full and (len(r.description) > DESC_MAX or len(r.purpose) > PURPOSE_MAX):
any_truncated = True
table.add_row(
r.code,
r.description,
r.purpose,
level_str,
str(len(r.agents)),
update_date,
r.id,
)
console.print(table)
if any_truncated:
rprint(f"[yellow]⚠ 部分字段已截断,完整规则文本共 {total_chars} 字符[/yellow]")
rprint("[dim]使用 --full 参数获取完整内容:ekb agent rules --full[/dim]")
-48
View File
@@ -1,48 +0,0 @@
"""ekb agent update <id>:修改 Agent 配置(表现层)
不导入 api 层;通过 services.update_agent_cmd 更新 Agent。
EkbError 由 CLI 入口全局 handler 统一处理,本层不 catch。
"""
from typing import Optional
import typer
from rich import print as rprint
from ekb_cli.services import update_agent_cmd, AgentUpdateInput, MODE_DISPLAY
STATE_DISPLAY = {0: "启用", 1: "禁用"}
def cmd_update(
agent_id: str = typer.Argument(..., help="Agent ID"),
name: Optional[str] = typer.Option(None, "--name", "-n", help="名称"),
description: Optional[str] = typer.Option(None, "--description", "-d", help="描述"),
mode: Optional[str] = typer.Option(None, "--mode", "-m", help="模式:auto/semi/assist"),
sampling_rate: Optional[int] = typer.Option(None, "--sampling-rate", "-r", help="半自动抽检比例 0-100"),
state: Optional[int] = typer.Option(None, "--state", "-s", help="状态:0=启用 1=禁用"),
agree_terms: Optional[str] = typer.Option(None, "--agree-terms", help="同意条款"),
reject_terms: Optional[str] = typer.Option(None, "--reject-terms", help="拒绝条款"),
exempt_terms: Optional[str] = typer.Option(None, "--exempt-terms", help="豁免条款"),
review_terms: Optional[str] = typer.Option(None, "--review-terms", help="转人工条款"),
):
"""修改 Agent 配置(只传需要修改的字段)"""
inp = AgentUpdateInput(
agent_id=agent_id,
name=name,
description=description,
mode=mode,
sampling_rate=sampling_rate,
state=state,
agree_terms=agree_terms,
reject_terms=reject_terms,
exempt_terms=exempt_terms,
review_terms=review_terms,
)
saved = update_agent_cmd(inp)
rprint(
f"[green]✓[/green] 已更新 Agent [bold]{saved.name}[/bold]"
f" 模式={MODE_DISPLAY.get(saved.mode, str(saved.mode))}"
f" 状态={STATE_DISPLAY.get(saved.state, str(saved.state))}"
)
-84
View File
@@ -1,84 +0,0 @@
"""auth 命令:管理企业认证信息
表现层:只负责参数解析、交互式输入、rich 格式化输出。
业务逻辑委托给 services.auth_service。
异常处理约定:
所有命令不做局部捕获,让 EkbError 冒泡到 CLI 入口的全局 handler,
由 __init__.py 统一以红字输出并 Exit(1)。
"""
import typer
from rich.console import Console
from rich.table import Table
from rich import print as rprint
from ekb_cli.services import auth_service
app = typer.Typer(help="管理企业认证")
console = Console()
@app.command("add")
def auth_add():
"""添加企业认证(从浏览器 F12 复制请求头中的 accesstoken / corpid / staffid)"""
console.print("\n[bold]添加企业认证[/bold]")
console.print("步骤:打开快报 → F12 → 任意 API 请求 → 请求头中找到以下三个字段\n")
# 交互式输入留在 CLI 层,service 层不涉及 I/O
access_token = typer.prompt("accesstoken").strip()
corp_id = typer.prompt("corpid").strip()
staff_id = typer.prompt("staffid").strip()
for label, val in [("accesstoken", access_token), ("corpid", corp_id), ("staffid", staff_id)]:
if not val:
rprint(f"[red]{label} 不能为空[/red]")
raise typer.Exit(1)
name = typer.prompt("企业名称(方便识别)", default=corp_id).strip()
corp = auth_service.add_corp(corp_id=corp_id, name=name,
access_token=access_token, staff_id=staff_id)
rprint(f"[green]✓[/green] 已添加企业 [bold]{corp.name}[/bold] ({corp.corp_id})")
@app.command("list")
def auth_list():
"""列出所有已添加的企业"""
corps = auth_service.list_corps()
if not corps:
rprint("[yellow]尚未添加任何企业,请先执行 `ekb auth add`[/yellow]")
raise typer.Exit()
table = Table(title="已配置的企业")
table.add_column("", width=2)
table.add_column("名称")
table.add_column("corpId")
for c in corps:
marker = "[green]*[/green]" if c.is_current else ""
table.add_row(marker, c.name, c.corp_id)
console.print(table)
@app.command("use")
def auth_use(corp_id: str = typer.Argument(..., help="要切换的企业 corpId")):
"""切换当前使用的企业"""
corp = auth_service.use_corp(corp_id)
rprint(f"[green]✓[/green] 已切换到企业 [bold]{corp.name}[/bold] ({corp.corp_id})")
@app.command("remove")
def auth_remove(corp_id: str = typer.Argument(..., help="要删除的企业 corpId")):
"""删除一个企业的认证信息"""
auth_service.remove_corp(corp_id)
rprint(f"[green]✓[/green] 已删除企业 {corp_id}")
@app.command("whoami")
def auth_whoami():
"""查看当前使用的企业"""
corp = auth_service.whoami()
rprint(f"当前企业:[bold]{corp.name}[/bold] ({corp.corp_id})")
-94
View File
@@ -1,94 +0,0 @@
"""ekb commands [GROUP]:查看命令树"""
from typing import Optional
import typer
from rich.console import Console
from rich.tree import Tree
console = Console()
# 命令树定义:新增命令组/命令时在此同步维护
COMMAND_TREE = {
"auth": {
"_help": "管理企业认证",
"add": "添加企业认证",
"list": "列出所有企业",
"use": "切换当前企业",
"remove": "删除企业",
"whoami": "查看当前企业",
},
"agent": {
"_help": "智能审核 Agent 管理",
"list": "列出所有 Agent",
"get": "查看 Agent 详情 → ekb agent get <id> --help",
"create": "新建 Agent → ekb agent create --help",
"copy": "复制 Agent(名称自动加「副本」) → ekb agent copy <id>",
"update": "修改 Agent 配置 → ekb agent update <id> --help",
"delete": "删除 Agent(有二次确认) → ekb agent delete <id>",
"rules": "列出所有审核规则 → ekb agent rules --help",
"rule-get": "查看规则详情 → ekb agent rule-get <id或编码>",
"rule-create": "新建审核规则 → ekb agent rule-create --help",
"logs": "查看审核日志",
},
"serve": {
"_help": "启动 HTTP API Server",
"--host": "监听地址(默认 127.0.0.1)",
"--port": "监听端口(默认 9528)",
"--reload": "开发模式自动重载",
},
"sealai": {
"_help": "SealAI 智能填单/审核平台管理",
"whoami": "查看当前 SealAI 用户身份及租户信息",
"billing": "查看当前企业 SealAI 订阅状态及功能配额",
"rules": "查看草稿区审核规则列表",
"rule-create": "新建草稿审核规则",
"rule-update": "更新草稿审核规则 → ekb sealai rule-update <id> --help",
"rule-delete": "删除草稿审核规则 → ekb sealai rule-delete <id>",
"versions": "查看已发布规则集版本历史",
"knowledge-list": "查看知识文档列表 → ekb sealai knowledge-list --help",
"knowledge-get": "查看单篇知识文档详情 → ekb sealai knowledge-get <id>",
"knowledge-create": "新建知识文档 → ekb sealai knowledge-create --help",
"knowledge-update": "更新知识文档 → ekb sealai knowledge-update <id> --help",
},
"platform": {
"_help": "自建应用(DataLink Platform)管理",
"list": "列出当前企业所有启用的自建应用",
"workflow-list": "列出指定应用的工作流 → ekb platform workflow-list <platform_id> --help",
"workflow-stats": "查看工作流执行统计 → ekb platform workflow-stats <platform_id>",
"workflow-charge": "查看企业工作流资源包配额",
},
}
def cmd_commands(group: Optional[str] = typer.Argument(None, help="命令组名称,如 auth / agent / serve")):
"""查看命令树(不带参数显示全树,带组名只看该分支)"""
if group is not None:
if group not in COMMAND_TREE:
console.print(f"[red]未知命令组:{group}[/red]")
raise typer.Exit(1)
_print_group(group, COMMAND_TREE[group])
else:
root = Tree("[bold]ekb[/bold]")
for grp, cmds in COMMAND_TREE.items():
_build_branch(root, grp, cmds)
console.print(root)
console.print("\n[dim]查看某组详情:ekb commands <group>[/dim]")
console.print("[dim]查看命令参数:ekb <group> <command> --help[/dim]")
def _build_branch(parent, grp: str, cmds: dict):
branch = parent.add(f"[bold cyan]{grp}[/bold cyan] {cmds.get('_help', '')}")
for cmd, desc in cmds.items():
if cmd == "_help":
continue
branch.add(f"[green]{cmd}[/green] {desc}")
def _print_group(grp: str, cmds: dict):
tree = Tree(f"[bold]ekb[/bold] [bold cyan]{grp}[/bold cyan] {cmds.get('_help', '')}")
for cmd, desc in cmds.items():
if cmd == "_help":
continue
tree.add(f"[green]{cmd}[/green] {desc}")
console.print(tree)
console.print(f"\n[dim]查看命令参数:ekb {grp} <command> --help[/dim]")
@@ -1,28 +0,0 @@
# commands/platform — 自建应用命令层
## 命令一览
| 命令 | 说明 |
|---|---|
| `ekb platform list` | 列出当前企业所有启用的自建应用 |
| `ekb platform workflow-list <platform_id>` | 分页列出指定应用的工作流 |
| `ekb platform workflow-stats <platform_id>` | 查看工作流执行统计 |
| `ekb platform workflow-charge` | 查看企业工作流资源包配额 |
## 文件说明
| 文件 | 对应命令 |
|---|---|
| `list.py` | `ekb platform list` |
| `workflow_list.py` | `ekb platform workflow-list` |
| `workflow_stats.py` | `ekb platform workflow-stats` |
| `workflow_charge.py` | `ekb platform workflow-charge` |
## 待实现(预留)
以下子模块待接口抓包后开发:
| 命令(待建) | 对应业务 |
|---|---|
| `ekb platform entity-list <platform_id>` | 业务对象(实体)列表 |
| `ekb platform page-list <platform_id>` | 页面设计器列表 |
-19
View File
@@ -1,19 +0,0 @@
"""platform 子命令组:自建应用管理"""
import typer
from ekb_cli.commands.platform.list import cmd_list
from ekb_cli.commands.platform.workflow_list import cmd_workflow_list
from ekb_cli.commands.platform.workflow_get import cmd_workflow_get
from ekb_cli.commands.platform.workflow_stats import cmd_workflow_stats
from ekb_cli.commands.platform.workflow_charge import cmd_workflow_charge
from ekb_cli.commands.platform.workflow_search import cmd_workflow_search
app = typer.Typer(help="自建应用(DataLink Platform)管理")
app.command("list")(cmd_list)
app.command("workflow-list")(cmd_workflow_list)
app.command("workflow-get")(cmd_workflow_get)
app.command("workflow-stats")(cmd_workflow_stats)
app.command("workflow-charge")(cmd_workflow_charge)
app.command("workflow-search")(cmd_workflow_search)
-36
View File
@@ -1,36 +0,0 @@
"""ekb platform list:列出当前企业下所有启用的自建应用"""
from rich.console import Console
from rich.table import Table
from rich import print as rprint
from ekb_cli.services.platform import list_platforms_cmd
console = Console()
def cmd_list():
"""列出当前企业所有启用的自建应用"""
platforms = list_platforms_cmd()
if not platforms:
rprint("[yellow]暂无自建应用[/yellow]")
return
table = Table(title="自建应用列表")
table.add_column("ID", style="dim")
table.add_column("名称")
table.add_column("编码")
table.add_column("类型")
table.add_column("状态")
for p in platforms:
table.add_row(
p.id,
p.name,
p.code,
p.platformType or p.groupType,
"[green]启用[/green]" if p.active else "[dim]停用[/dim]",
)
console.print(table)
@@ -1,26 +0,0 @@
"""ekb platform workflow-charge:查看企业工作流资源包/配额"""
from rich.console import Console
from rich.table import Table
from ekb_cli.services.platform import get_workflow_charge_cmd
console = Console()
def cmd_workflow_charge():
"""查看企业工作流资源包配额"""
charge = get_workflow_charge_cmd()
table = Table(title="工作流资源包配额")
table.add_column("指标")
table.add_column("数值", justify="right")
table.add_row("企业 ID", charge.corporationId)
table.add_row("订购状态", charge.status)
table.add_row("套餐类型", charge.orderType)
table.add_row("总配额", str(charge.total))
table.add_row("已使用", str(charge.used))
table.add_row("剩余", str(charge.remaining))
console.print(table)
@@ -1,54 +0,0 @@
"""ekb platform workflow-get:查看工作流完整配置(节点列表)"""
import typer
from rich.console import Console
from rich.table import Table
from rich import print as rprint
from ekb_cli.services.platform import get_workflow_cmd
console = Console()
GROUP_LABEL = {"trigger": "触发", "action": "动作", "control": "控制"}
STATE_LABEL = {"success": "[green]✓[/green]", "error": "[red]✗[/red]", "": ""}
def cmd_workflow_get(
platform_id: str = typer.Argument(..., help="自建应用 ID"),
pipeline_id: str = typer.Argument(..., help="工作流 ID"),
):
"""查看指定工作流的完整配置(触发器 + 节点列表)"""
wf = get_workflow_cmd(platform_id, pipeline_id)
state_text = "[green]启用[/green]" if wf.state == 1 else "[dim]停用[/dim]"
console.print(f"\n[bold]{wf.label}[/bold] {state_text} [dim]v{wf.version}[/dim]")
if wf.desc:
console.print(f"[dim]{wf.desc}[/dim]")
console.print(
f"执行 {wf.runTimes} 次 / 失败 {wf.errorTimes} 次 "
f"更新:{wf.updateTime} 更新人:{wf.updateUser or '-'}\n"
)
if not wf.tasks:
rprint("[yellow]暂无节点[/yellow]")
return
table = Table(title=f"节点列表(共 {len(wf.tasks)} 个)", show_lines=True)
table.add_column("步骤", style="bold", justify="right")
table.add_column("类型")
table.add_column("名称")
table.add_column("分组")
table.add_column("描述")
table.add_column("状态", justify="center")
for task in wf.tasks:
table.add_row(
str(task.orderIndex),
task.type,
task.label,
GROUP_LABEL.get(task.groupName, task.groupName),
(task.desc or "")[:60],
STATE_LABEL.get(task.status, task.status),
)
console.print(table)
@@ -1,47 +0,0 @@
"""ekb platform workflow-list:列出指定自建应用下的工作流"""
import typer
from rich.console import Console
from rich.table import Table
from rich import print as rprint
from ekb_cli.services.platform import list_workflows_cmd
console = Console()
STATE_MAP = {0: "[dim]停用[/dim]", 1: "[green]启用[/green]"}
def cmd_workflow_list(
platform_id: str = typer.Argument(..., help="自建应用 ID"),
page: int = typer.Option(1, "--page", "-p", help="页码(从 1 开始)"),
page_size: int = typer.Option(20, "--page-size", "-s", help="每页数量"),
):
"""列出指定自建应用下的工作流(分页)"""
result = list_workflows_cmd(platform_id, page=page, page_size=page_size)
if not result.pipelineList:
rprint("[yellow]暂无工作流[/yellow]")
return
table = Table(
title=f"工作流列表(应用 {platform_id},第 {result.number}/{result.totalPages} 页,共 {result.pipelineNum} 条)"
)
table.add_column("ID", style="dim")
table.add_column("名称")
table.add_column("状态")
table.add_column("运行中")
table.add_column("失败")
table.add_column("更新时间")
for wf in result.pipelineList:
table.add_row(
wf.id,
wf.pipelineName,
STATE_MAP.get(wf.state, str(wf.state)),
str(wf.runningCount),
str(wf.errorCount),
wf.updateTime,
)
console.print(table)
@@ -1,42 +0,0 @@
"""ekb platform workflow-search:跨所有自建应用查找含指定节点类型的工作流"""
import typer
from rich.console import Console
from rich.table import Table
from rich import print as rprint
from ekb_cli.services.platform import find_workflows_by_task_type_cmd
console = Console()
def cmd_workflow_search(
task_type: str = typer.Argument(..., help="节点类型,如 http / ekuaibao-ebot-trigger / stop"),
all_states: bool = typer.Option(False, "--all", "-a", help="包含已停用的工作流(默认只查启用)"),
):
"""跨所有自建应用,查找含指定节点类型的工作流"""
enabled_only = not all_states
matches = find_workflows_by_task_type_cmd(task_type, enabled_only=enabled_only)
if not matches:
rprint(f"[yellow]未找到含 [bold]{task_type}[/bold] 节点的工作流[/yellow]")
return
table = Table(
title=f"含 {task_type} 节点的工作流(共 {len(matches)} 个)",
show_lines=True,
)
table.add_column("自建应用", style="cyan")
table.add_column("工作流名称")
table.add_column("工作流 ID", style="dim")
table.add_column("节点数", justify="center", style="bold yellow")
for m in matches:
table.add_row(
m.platform_name,
m.workflow_name,
m.workflow_id,
str(len(m.matched_tasks)),
)
console.print(table)
@@ -1,30 +0,0 @@
"""ekb platform workflow-stats:查看指定自建应用的工作流执行统计"""
import typer
from rich.console import Console
from rich.table import Table
from ekb_cli.services.platform import get_workflow_stats_cmd
console = Console()
def cmd_workflow_stats(
platform_id: str = typer.Argument(..., help="自建应用 ID"),
):
"""查看指定自建应用的工作流执行统计"""
stats = get_workflow_stats_cmd(platform_id)
table = Table(title=f"工作流执行统计(应用 {platform_id})")
table.add_column("指标")
table.add_column("数值", justify="right")
table.add_row("总执行次数", str(stats.total))
table.add_row("已完成", str(stats.completed))
table.add_row("失败", str(stats.failed))
table.add_row("进行中", str(stats.started))
table.add_row("已启用工作流", str(stats.pipelineOpenCount))
table.add_row("已停用工作流", str(stats.pipelineCloseCount))
table.add_row("工作流总数", str(stats.pipelineAllCount))
console.print(table)
@@ -1,163 +0,0 @@
# commands/sealai/ — SealAI 命令层说明
SealAI(`{corpId.lower()}.sealai.cc`)是独立于快报主站的 AI 填单/审批平台,
认证体系与快报 HAB 完全独立(Bearer JWT)。
本目录是 **表现层**,只负责 CLI 参数解析和 rich 输出,所有业务逻辑和 client
生命周期管理统一由 `services/sealai/` 承担。
---
## 目录分层
```
api/sealai/
├── client.py SealAiClient(httpx,Bearer JWT 认证)
├── schemas.py Pydantic 数据模型
├── auth_api.py GET /api/v1/auth/me
├── billing_api.py GET /api/v1/billing/status
├── rules_api.py 草稿规则 CRUD + 已发布版本历史
├── preference_api.py AI 审批风格偏好读写
└── knowledge_api.py 知识文档 CRUD
services/sealai/
├── auth_service.py SSO token 换取 + 双层缓存 + 401 自动恢复
├── billing_service.py 订阅状态查询 + 单功能配额查询
├── rules_service.py 草稿规则 CRUD + 版本发布
├── preference_service.py AI 审批风格偏好读写
└── knowledge_service.py 知识文档 CRUD
commands/sealai/(本目录)
├── whoami.py ekb sealai whoami
├── billing.py ekb sealai billing
├── rules.py ekb sealai rules
├── rule_create.py ekb sealai rule-create
├── rule_update.py ekb sealai rule-update
├── rule_delete.py ekb sealai rule-delete
├── versions.py ekb sealai versions
├── knowledge_list.py ekb sealai knowledge-list
├── knowledge_get.py ekb sealai knowledge-get
├── knowledge_create.py ekb sealai knowledge-create
└── knowledge_update.py ekb sealai knowledge-update
server/sealai_router.py /sealai/* HTTP 路由(同 CLI 命令对应的 Server 端)
```
---
## 认证流程
```
快报 accesstoken
→ GET https://{corpId.lower()}.sealai.cc/api/auth/oauth2/session/oem-hosecloud
?token={accesstoken}&returnToken=1
→ Bearer JWT
→ 写入磁盘缓存 ~/.config/ekb-cli/sealai_tokens.json(TTL 1 小时)
→ 构造 SealAiClient(corp_id, bearer_token),写入模块级内存缓存
内存缓存在 TTL 内复用(Server 复用连接池;CLI 进程结束自然回收)
401 时 _sealai_call 自动清除双层缓存并重试一次,调用方无感知
```
- corpId 转小写作为子域名:`ID01Jdq2yIDnMr` → `id01jdq2yidnmr.sealai.cc`
- 磁盘缓存格式:`{ "corpId": { "token": "...", "fetched_at": 1712345678 } }`
---
## 已知 API 路径
> `client.get/post/put/patch/delete(path)` 直接传完整路径(含 `/api` 前缀)。
```
# 认证
GET /api/v1/auth/me 当前用户身份(user + tenant)
# 计费
GET /api/v1/billing/status 订阅状态 + 各功能配额
# 审核规则(草稿区)
GET /api/v1/rules 草稿规则列表
POST /api/v1/rules 新建草稿规则(description/scope/strictness)
PUT /api/v1/rules/{id} 更新草稿规则(partial)
DELETE /api/v1/rules/{id} 删除草稿规则
# 审核规则(已发布版本)
GET /api/v1/rule-set-versions 已发布版本列表(倒序)
POST /api/v1/rule-set-versions/publish 发布当前草稿为新版本
# AI 审批风格偏好
GET /api/v1/ai-approval/config 读取完整偏好配置
POST /api/v1/ai-approval/config 整体替换偏好配置
PATCH /api/v1/ai-approval/config/decision-preferences Patch 式更新决策偏好
# 知识文档
GET /api/v1/knowledge/articles 知识文档列表(支持场景过滤、分页、排序)
POST /api/v1/knowledge/articles 新建知识文档
GET /api/v1/knowledge/articles/{id} 知识文档详情
PATCH /api/v1/knowledge/articles/{id} 更新知识文档(partial)
```
### strictness 枚举值
| 值 | 含义 |
|----|------|
| `MUST_FOLLOW` | 必须遵守 |
| `SHOULD_FOLLOW` | 应当遵守 |
| `SUGGESTION` | 建议 |
---
## 功能项(Feature)说明
| code | 名称 | 类型 | 说明 |
|------|------|------|------|
| `ai-approval` | AI 审批 | 余额型 | balance/totalQuota/totalUsed |
| `approval-rules` | 审核规则 | 配额型 | quota/used/remaining |
| `financial-policies` | 财务制度 | 配额型 | quota/used/remaining |
| `knowledge-documents` | 知识文档 | 配额型 | quota/used/remaining |
| `webhook` | Webhook | 开关型 | enabled |
| `openapi` | Open API | 开关型 | enabled |
| `private-model` | 私有模型接入 | 开关型 | enabled |
| `ai-fill` | AI 智能填单 | 开关型 | enabled |
---
## CLI 命令速查
```bash
# 认证 / 身份
ekb sealai whoami # 查看 SealAI 用户身份 + 租户信息
ekb sealai whoami --refresh # 强制刷新 Bearer token 后查看
ekb sealai whoami --corp <corpId> # 查看指定企业
# 计费
ekb sealai billing # 查看订阅状态 + 功能配额表
ekb sealai billing --corp <corpId>
# 审核规则
ekb sealai rules # 查看草稿区规则列表
ekb sealai rule-create # 新建草稿规则(交互式)
ekb sealai rule-create --desc "..." --scope "..." --strictness MUST_FOLLOW
ekb sealai rule-update <ruleId> --desc "..."
ekb sealai rule-delete <ruleId>
# 版本历史
ekb sealai versions # 查看已发布版本列表
# 知识文档
ekb sealai knowledge-list # 查看知识文档列表
ekb sealai knowledge-list --scenario audit --scenario fill
ekb sealai knowledge-get <articleId> # 查看文档详情
ekb sealai knowledge-create # 新建文档(交互式)
ekb sealai knowledge-create --title "..." --purpose "..." --content "..."
ekb sealai knowledge-update <articleId> --title "新标题"
ekb sealai knowledge-update <articleId> --disable
```
---
## 调用约定
- `commands/sealai/*` 只传 `corp_id`,不持有也不传递 `SealAiClient`
- `SealAiClient` 的创建、缓存、关闭完全由 `services/sealai/auth_service.py` 管理
- 详细缓存设计见 `services/sealai/README.sealai.md`
-43
View File
@@ -1,43 +0,0 @@
"""sealai 子命令组
对应 CLI 命令:
ekb sealai whoami → 查看当前 SealAI 用户身份及租户信息
ekb sealai billing → 查看当前企业 SealAI 订阅状态及功能配额
ekb sealai rules → 查看草稿区审核规则列表
ekb sealai rule-create → 新建草稿审核规则
ekb sealai rule-update → 更新草稿审核规则
ekb sealai rule-delete → 删除草稿审核规则
ekb sealai versions → 查看已发布规则集版本历史
ekb sealai knowledge-list → 查看知识文档列表
ekb sealai knowledge-get → 查看单篇知识文档详情
ekb sealai knowledge-create → 新建知识文档
ekb sealai knowledge-update → 更新知识文档
"""
import typer
from ekb_cli.commands.sealai.whoami import cmd_whoami
from ekb_cli.commands.sealai.billing import cmd_billing
from ekb_cli.commands.sealai.rules import cmd_rules
from ekb_cli.commands.sealai.rule_create import cmd_rule_create
from ekb_cli.commands.sealai.rule_update import cmd_rule_update
from ekb_cli.commands.sealai.rule_delete import cmd_rule_delete
from ekb_cli.commands.sealai.versions import cmd_versions
from ekb_cli.commands.sealai.knowledge_list import cmd_knowledge_list
from ekb_cli.commands.sealai.knowledge_get import cmd_knowledge_get
from ekb_cli.commands.sealai.knowledge_create import cmd_knowledge_create
from ekb_cli.commands.sealai.knowledge_update import cmd_knowledge_update
app = typer.Typer(help="SealAI 智能填单/审核平台管理")
app.command("whoami")(cmd_whoami)
app.command("billing")(cmd_billing)
app.command("rules")(cmd_rules)
app.command("rule-create")(cmd_rule_create)
app.command("rule-update")(cmd_rule_update)
app.command("rule-delete")(cmd_rule_delete)
app.command("versions")(cmd_versions)
app.command("knowledge-list")(cmd_knowledge_list)
app.command("knowledge-get")(cmd_knowledge_get)
app.command("knowledge-create")(cmd_knowledge_create)
app.command("knowledge-update")(cmd_knowledge_update)
-63
View File
@@ -1,63 +0,0 @@
"""sealai billing:查看 SealAI 订阅状态及功能配额
表现层:只负责 rich 格式化输出。
业务逻辑委托给 services.sealai.billing_service。
不感知 SealAiClient,corp_id 由 service 层统一解析。
"""
import typer
from rich.console import Console
from rich.table import Table
from rich import print as rprint
from ekb_cli.services.sealai import query_billing_status
console = Console()
def cmd_billing(
corp_id: str = typer.Option(None, "--corp", "-c", help="指定企业 corpId,默认使用当前企业"),
):
"""查看当前企业 SealAI 订阅状态及各功能配额"""
status = query_billing_status(corp_id=corp_id)
# 订阅信息
if status.subscriptions:
sub = status.subscriptions[0]
console.print(f"\n[bold]订阅信息[/bold]")
table = Table(show_header=False, box=None, padding=(0, 2))
table.add_column("字段", style="dim")
table.add_column("值")
table.add_row("订阅 ID", sub.id)
table.add_row("状态", "[green]生效中[/green]" if sub.status == "active" else sub.status)
table.add_row("开始日期", sub.startDate)
console.print(table)
else:
rprint("[yellow]当前企业无有效订阅[/yellow]")
# 功能配额表
if not status.features:
return
console.print(f"\n[bold]功能配额[/bold]")
feat_table = Table(show_header=True, header_style="bold")
feat_table.add_column("功能名称")
feat_table.add_column("code", style="dim")
feat_table.add_column("状态/用量", justify="right")
for f in status.features:
if f.enabled is not None:
# 开关型
usage = "[green]已开启[/green]" if f.enabled else "[red]未开启[/red]"
elif f.balance is not None:
# 余额型
usage = f"余额 {f.balance}/{f.totalQuota}"
elif f.quota is not None:
# 配额型
usage = f"已用 {f.used}/{f.quota}"
else:
usage = "-"
feat_table.add_row(f.name, f.code, usage)
console.print(feat_table)
console.print()
@@ -1,56 +0,0 @@
"""sealai knowledge-create:新建知识文档
表现层:交互式输入 + rich 输出。
业务逻辑委托给 services.sealai.knowledge_service。
不感知 SealAiClient,corp_id 由 service 层统一解析。
"""
import typer
from rich import print as rprint
from ekb_cli.services.sealai import add_article
def cmd_knowledge_create(
corp_id: str = typer.Option(None, "--corp", "-c", help="指定企业 corpId,默认使用当前企业"),
title: str = typer.Option(None, "--title", "-t", help="文档标题"),
purpose: str = typer.Option(None, "--purpose", "-p", help="适用说明"),
content: str = typer.Option(None, "--content", help="正文内容(Markdown),不传则交互输入"),
content_type: str = typer.Option("policy", "--type", help="内容类型,默认 policy"),
status: str = typer.Option("published", "--status", help="状态:published / draft"),
scenarios: list[str] = typer.Option([], "--scenario", "-s", help="适用场景(可多次传),如 -s audit -s fill"),
tags: list[str] = typer.Option([], "--tag", help="标签(可多次传),如 --tag __all__"),
):
"""新建知识文档"""
if title is None:
title = typer.prompt("文档标题").strip()
if purpose is None:
purpose = typer.prompt("适用说明").strip()
if not title or not purpose:
rprint("[red]标题和适用说明不能为空[/red]")
raise typer.Exit(1)
if content is None:
rprint("[dim]请输入正文内容(Markdown 格式),输入完毕后按 Enter 再输入 EOF 结束:[/dim]")
lines = []
try:
while True:
line = input()
if line == "EOF":
break
lines.append(line)
except EOFError:
pass
content = "\n".join(lines)
article = add_article(
corp_id=corp_id,
title=title,
purpose=purpose,
content=content,
content_type=content_type,
status=status,
scenarios=list(scenarios) or None,
tags=list(tags) or None,
)
rprint(f"[green]✓[/green] 文档已创建:[bold]{article.title}[/bold]")
rprint(f" ID:[dim]{article.id}[/dim]")
@@ -1,63 +0,0 @@
"""sealai knowledge-get:查看单篇知识文档详情
表现层:只负责 rich 格式化输出。
业务逻辑委托给 services.sealai.knowledge_service。
不感知 SealAiClient,corp_id 由 service 层统一解析。
"""
import typer
from datetime import datetime, timezone
from rich.console import Console
from rich.panel import Panel
from rich.markdown import Markdown
from rich.table import Table
from rich import print as rprint
from ekb_cli.services.sealai import get_article_detail
console = Console()
_SCENARIO_LABEL = {
"audit": "审核",
"fill": "填单",
}
_STATUS_LABEL = {
"published": "[green]已发布[/green]",
"draft": "[yellow]草稿[/yellow]",
}
def cmd_knowledge_get(
article_id: str = typer.Argument(..., help="文档 ID"),
corp_id: str = typer.Option(None, "--corp", "-c", help="指定企业 corpId,默认使用当前企业"),
):
"""查看单篇知识文档详情(含正文 Markdown 渲染)"""
a = get_article_detail(corp_id=corp_id, article_id=article_id)
scenes = " / ".join(_SCENARIO_LABEL.get(s, s) for s in a.scenarios)
status = _STATUS_LABEL.get(a.status, a.status)
enabled = "[green]启用[/green]" if a.enabled else "[red]已禁用[/red]"
tags_str = "、".join(a.tags) if a.tags else "[dim]无[/dim]"
# 元信息表格
meta = Table.grid(padding=(0, 2))
meta.add_column(style="dim")
meta.add_column()
meta.add_row("ID", a.id)
meta.add_row("标题", a.title)
meta.add_row("适用说明", a.purpose)
meta.add_row("内容类型", a.contentType)
meta.add_row("适用场景", scenes)
meta.add_row("标签", tags_str)
meta.add_row("状态", f"{status} {enabled}")
if a.createdAt:
ts = datetime.fromtimestamp(a.createdAt / 1000, tz=timezone.utc).strftime("%Y-%m-%d %H:%M")
meta.add_row("创建时间", f"{ts} by {a.createdByName}")
if a.updatedAt:
ts = datetime.fromtimestamp(a.updatedAt / 1000, tz=timezone.utc).strftime("%Y-%m-%d %H:%M")
meta.add_row("更新时间", f"{ts} by {a.updatedByName}")
console.print(meta)
console.print()
console.print(Panel(Markdown(a.content), title="[bold]正文内容[/bold]", border_style="dim"))
@@ -1,70 +0,0 @@
"""sealai knowledge-list:查看知识文档列表
表现层:只负责 rich 格式化输出。
业务逻辑委托给 services.sealai.knowledge_service。
不感知 SealAiClient,corp_id 由 service 层统一解析。
"""
import typer
from datetime import datetime, timezone
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.markdown import Markdown
from rich import print as rprint
from ekb_cli.services.sealai import get_articles
console = Console()
_SCENARIO_LABEL = {
"audit": "审核",
"fill": "填单",
}
_STATUS_LABEL = {
"published": "[green]已发布[/green]",
"draft": "[yellow]草稿[/yellow]",
}
def cmd_knowledge_list(
corp_id: str = typer.Option(None, "--corp", "-c", help="指定企业 corpId,默认使用当前企业"),
scenario: str = typer.Option(None, "--scenario", "-s", help="按场景过滤:audit / fill"),
limit: int = typer.Option(20, "--limit", "-n", help="返回数量上限"),
detail: bool = typer.Option(False, "--detail", help="展开每篇文档的正文内容"),
):
"""查看知识文档列表"""
scenarios = [scenario] if scenario else None
data = get_articles(corp_id=corp_id, scenarios=scenarios, limit=limit)
if not data.articles:
rprint("[yellow]暂无知识文档[/yellow]")
raise typer.Exit()
if not detail:
table = Table(title=f"知识文档(共 {data.total or len(data.articles)} 篇)", show_lines=True)
table.add_column("ID", style="dim", no_wrap=True)
table.add_column("标题")
table.add_column("适用说明", max_width=30)
table.add_column("场景")
table.add_column("状态")
table.add_column("更新时间")
for a in data.articles:
scenes = " / ".join(_SCENARIO_LABEL.get(s, s) for s in a.scenarios)
status = _STATUS_LABEL.get(a.status, a.status)
ts = datetime.fromtimestamp(a.updatedAt / 1000, tz=timezone.utc).strftime("%Y-%m-%d %H:%M") if a.updatedAt else "-"
table.add_row(a.id[:8] + "…", a.title, a.purpose, scenes, status, ts)
console.print(table)
console.print("[dim]查看正文内容:ekb sealai knowledge-list --detail[/dim]")
console.print("[dim]查看单篇详情:ekb sealai knowledge-get <id>[/dim]")
else:
for a in data.articles:
scenes = " / ".join(_SCENARIO_LABEL.get(s, s) for s in a.scenarios)
status = _STATUS_LABEL.get(a.status, a.status)
console.print(Panel(
Markdown(a.content),
title=f"[bold]{a.title}[/bold] {status} [dim]{scenes}[/dim]",
subtitle=f"[dim]ID: {a.id}[/dim]",
))
@@ -1,48 +0,0 @@
"""sealai knowledge-update:更新知识文档
表现层:只负责参数解析 + rich 输出。
业务逻辑委托给 services.sealai.knowledge_service。
不感知 SealAiClient,corp_id 由 service 层统一解析。
"""
import typer
from typing import Optional
from rich import print as rprint
from ekb_cli.services.sealai import edit_article
def cmd_knowledge_update(
article_id: str = typer.Argument(..., help="文档 ID"),
corp_id: str = typer.Option(None, "--corp", "-c", help="指定企业 corpId,默认使用当前企业"),
title: str = typer.Option(None, "--title", "-t", help="新标题"),
purpose: str = typer.Option(None, "--purpose", "-p", help="新适用说明"),
content: str = typer.Option(None, "--content", help="新正文内容(Markdown)"),
content_type: str = typer.Option(None, "--type", help="新内容类型"),
status: str = typer.Option(None, "--status", help="新状态:published / draft"),
enable: bool = typer.Option(None, "--enable/--disable", help="启用或停用文档"),
scenarios: Optional[list[str]] = typer.Option(None, "--scenario", "-s", help="新适用场景(可多次传,会整体替换)"),
tags: Optional[list[str]] = typer.Option(None, "--tag", help="新标签(可多次传,会整体替换)"),
):
"""更新知识文档(只传需要修改的字段)"""
# enable 是 Optional[bool],typer 的 --enable/--disable 未传时值为 None
any_field = any([title, purpose, content, content_type, status, scenarios, tags, enable is not None])
if not any_field:
rprint("[yellow]未指定任何修改字段,无需更新[/yellow]")
raise typer.Exit()
article = edit_article(
corp_id=corp_id,
article_id=article_id,
title=title,
purpose=purpose,
content=content,
content_type=content_type,
status=status,
enabled=enable,
scenarios=list(scenarios) if scenarios is not None else None,
tags=list(tags) if tags is not None else None,
)
enabled_str = "[green]启用[/green]" if article.enabled else "[red]已停用[/red]"
rprint(f"[green]✓[/green] 文档已更新:[bold]{article.title}[/bold] {enabled_str}")
rprint(f" ID:[dim]{article.id}[/dim]")
@@ -1,35 +0,0 @@
"""sealai rule-create:新建草稿审核规则
表现层:交互式输入 + rich 输出。
业务逻辑委托给 services.sealai.rules_service。
不感知 SealAiClient,corp_id 由 service 层统一解析。
"""
import typer
from rich import print as rprint
from ekb_cli.services.sealai import add_draft_rule
_STRICTNESS_CHOICES = ["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]
def cmd_rule_create(
corp_id: str = typer.Option(None, "--corp", "-c", help="指定企业 corpId,默认使用当前企业"),
description: str = typer.Option(None, "--description", "-d", help="规则描述"),
scope: str = typer.Option(None, "--scope", "-s", help="适用场景(费用类型等)"),
strictness: str = typer.Option(
"MUST_FOLLOW", "--strictness",
help="严格程度:MUST_FOLLOW / SHOULD_FOLLOW / SUGGESTION",
),
):
"""新建草稿审核规则"""
if description is None:
description = typer.prompt("规则描述").strip()
if scope is None:
scope = typer.prompt("适用场景").strip()
if not description or not scope:
rprint("[red]描述和适用场景不能为空[/red]")
raise typer.Exit(1)
rule = add_draft_rule(corp_id=corp_id, description=description, scope=scope, strictness=strictness)
rprint(f"[green]✓[/green] 规则已创建:[bold]{rule.description}[/bold](ID: {rule.id})")
@@ -1,27 +0,0 @@
"""sealai rule-delete:删除草稿审核规则
表现层:二次确认 + rich 输出。
业务逻辑委托给 services.sealai.rules_service。
不感知 SealAiClient,corp_id 由 service 层统一解析。
"""
import typer
from rich import print as rprint
from ekb_cli.services.sealai import remove_draft_rule
def cmd_rule_delete(
rule_id: str = typer.Argument(..., help="草稿规则 ID"),
yes: bool = typer.Option(False, "--yes", "-y", help="跳过确认直接删除"),
corp_id: str = typer.Option(None, "--corp", "-c", help="指定企业 corpId,默认使用当前企业"),
):
"""删除草稿审核规则"""
if not yes:
confirmed = typer.confirm(f"确定要删除规则 {rule_id}?")
if not confirmed:
rprint("[dim]已取消[/dim]")
raise typer.Exit()
remove_draft_rule(corp_id=corp_id, rule_id=rule_id)
rprint(f"[green]✓[/green] 规则 {rule_id} 已删除")
@@ -1,35 +0,0 @@
"""sealai rule-update:更新草稿审核规则
表现层:只负责参数解析 + rich 输出。
业务逻辑委托给 services.sealai.rules_service。
不感知 SealAiClient,corp_id 由 service 层统一解析。
"""
import typer
from rich import print as rprint
from ekb_cli.services.sealai import edit_draft_rule
def cmd_rule_update(
rule_id: str = typer.Argument(..., help="草稿规则 ID"),
description: str = typer.Option(None, "--description", "-d", help="新描述"),
scope: str = typer.Option(None, "--scope", "-s", help="新适用场景"),
strictness: str = typer.Option(
None, "--strictness",
help="新严格程度:MUST_FOLLOW / SHOULD_FOLLOW / SUGGESTION",
),
corp_id: str = typer.Option(None, "--corp", "-c", help="指定企业 corpId,默认使用当前企业"),
):
"""更新草稿审核规则(只传要修改的字段)"""
if not any([description, scope, strictness]):
rprint("[yellow]未指定任何修改字段,无需更新[/yellow]")
raise typer.Exit()
rule = edit_draft_rule(
corp_id=corp_id, rule_id=rule_id,
description=description,
scope=scope,
strictness=strictness,
)
rprint(f"[green]✓[/green] 规则已更新:[bold]{rule.description}[/bold](ID: {rule.id})")
-46
View File
@@ -1,46 +0,0 @@
"""sealai rules:查看草稿规则列表
表现层:只负责 rich 格式化输出。
业务逻辑委托给 services.sealai.rules_service。
不感知 SealAiClient,corp_id 由 service 层统一解析。
"""
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_draft_rules
console = Console()
_STRICTNESS_LABEL = {
"MUST_FOLLOW": "[red]必须遵守[/red]",
"SHOULD_FOLLOW": "[yellow]应当遵守[/yellow]",
"SUGGESTION": "[dim]建议[/dim]",
}
def cmd_rules(
corp_id: str = typer.Option(None, "--corp", "-c", help="指定企业 corpId,默认使用当前企业"),
):
"""查看草稿区所有审核规则"""
data = get_draft_rules(corp_id=corp_id)
if not data.rules:
rprint("[yellow]草稿区暂无审核规则[/yellow]")
raise typer.Exit()
table = Table(title=f"草稿审核规则(共 {len(data.rules)} 条)", show_lines=True)
table.add_column("ID", style="dim", no_wrap=True)
table.add_column("描述")
table.add_column("适用场景")
table.add_column("严格程度")
for r in data.rules:
label = _STRICTNESS_LABEL.get(r.strictness, r.strictness)
table.add_row(r.id[:8] + "…", r.description, r.scope, label)
console.print(table)
if data.hasPendingDeletes:
rprint("[yellow]⚠ 草稿区有待删除规则,发布后生效[/yellow]")
-66
View File
@@ -1,66 +0,0 @@
"""sealai versions:查看已发布规则集版本历史
表现层:只负责 rich 格式化输出。
业务逻辑委托给 services.sealai.rules_service。
不感知 SealAiClient,corp_id 由 service 层统一解析。
"""
import typer
from datetime import datetime, timezone
from rich.console import Console
from rich.table import Table
from rich.tree import Tree
from rich import print as rprint
from ekb_cli.services.sealai import get_published_versions
console = Console()
_STRICTNESS_LABEL = {
"MUST_FOLLOW": "必须",
"SHOULD_FOLLOW": "应当",
"SUGGESTION": "建议",
}
def cmd_versions(
corp_id: str = typer.Option(None, "--corp", "-c", help="指定企业 corpId,默认使用当前企业"),
detail: bool = typer.Option(False, "--detail", help="展开每个版本的规则列表"),
):
"""查看已发布规则集版本历史"""
versions = get_published_versions(corp_id=corp_id)
if not versions:
rprint("[yellow]暂无已发布版本[/yellow]")
raise typer.Exit()
if not detail:
table = Table(title=f"已发布版本(共 {len(versions)} 个)")
table.add_column("版本号", justify="right")
table.add_column("版本名称")
table.add_column("发布者")
table.add_column("规则数", justify="right")
table.add_column("发布时间")
for v in versions:
ts = datetime.fromtimestamp(v.publishedAt / 1000, tz=timezone.utc).strftime("%Y-%m-%d %H:%M")
table.add_row(
str(v.versionNumber),
v.versionName,
v.publishedByName,
str(len(v.rules)),
ts,
)
console.print(table)
console.print("[dim]查看规则详情:ekb sealai versions --detail[/dim]")
else:
for v in versions:
ts = datetime.fromtimestamp(v.publishedAt / 1000, tz=timezone.utc).strftime("%Y-%m-%d %H:%M")
tree = Tree(
f"[bold cyan]版本 {v.versionNumber}[/bold cyan] {v.versionName} "
f"[dim]{v.publishedByName} · {ts}[/dim]"
)
for r in v.rules:
label = _STRICTNESS_LABEL.get(r.strictness, r.strictness)
tree.add(f"[green]{label}[/green] {r.description} [dim]({r.scope})[/dim]")
console.print(tree)
-47
View File
@@ -1,47 +0,0 @@
"""sealai whoami:查看当前 SealAI 用户身份
表现层:只负责 rich 格式化输出。
业务逻辑(含 get_me 调用)完全委托给 services.sealai.get_whoami,
不直接导入 api 层任何函数。
"""
import typer
from rich.console import Console
from rich.table import Table
from ekb_cli.services.sealai import get_whoami
console = Console()
def cmd_whoami(
corp_id: str = typer.Option(None, "--corp", "-c", help="指定企业 corpId,默认使用当前企业"),
refresh: bool = typer.Option(False, "--refresh", help="强制刷新 SealAI Bearer token"),
):
"""查看当前 SealAI 用户身份及租户信息"""
me = get_whoami(corp_id=corp_id, force_refresh=refresh)
user = me.user
tenant = me.tenant
# 用户信息
console.print(f"\n[bold]SealAI 用户[/bold]")
table = Table(show_header=False, box=None, padding=(0, 2))
table.add_column("字段", style="dim")
table.add_column("值")
table.add_row("姓名", user.name)
table.add_row("用户 ID", user.id)
table.add_row("是否管理员", "[green]是[/green]" if user.isAdmin else "否")
table.add_row("快报 staffId", user.providerUserId)
console.print(table)
# 租户信息
console.print(f"\n[bold]租户(企业)[/bold]")
table2 = Table(show_header=False, box=None, padding=(0, 2))
table2.add_column("字段", style="dim")
table2.add_column("值")
table2.add_row("企业名称", tenant.name)
table2.add_row("租户 Slug", tenant.tenantSlug)
table2.add_row("企业 ID(快报)", tenant.hoseCorpConfig.corporationId)
console.print(table2)
console.print()
-38
View File
@@ -1,38 +0,0 @@
"""ekb serve:启动 HTTP API Server
将 ekb-cli 的功能以 HTTP API 形式暴露,
供其他服务、AI Agent 或脚本调用,返回结构化 JSON 数据。
"""
import typer
from rich import print as rprint
def cmd_serve(
host: str = typer.Option("127.0.0.1", "--host", "-h", help="监听地址"),
port: int = typer.Option(9528, "--port", "-p", help="监听端口"),
reload: bool = typer.Option(False, "--reload", help="开发模式:文件变更时自动重载"),
):
"""启动 HTTP API Server(FastAPI + uvicorn)
启动后可访问:
\b
- API 文档:http://<host>:<port>/docs
- 所有接口与 CLI 命令一一对应,返回结构化 JSON
"""
try:
import uvicorn
except ImportError:
rprint("[red]缺少 uvicorn,请执行:uv add uvicorn[standard][/red]")
raise typer.Exit(1)
from ekb_cli.server import create_app
rprint(f"[bold green]ekb-cli API Server[/bold green]")
rprint(f" 地址:http://{host}:{port}")
rprint(f" 文档:[link=http://{host}:{port}/docs]http://{host}:{port}/docs[/link]")
rprint(f" 模式:{'[yellow]开发(--reload)[/yellow]' if reload else '生产'}")
rprint("")
app = create_app()
uvicorn.run(app, host=host, port=port, reload=reload)
-65
View File
@@ -1,65 +0,0 @@
"""配置管理:存储多企业认证信息到 ~/.config/ekb-cli/config.json"""
import json
from pathlib import Path
from typing import Optional
CONFIG_DIR = Path.home() / ".config" / "ekb-cli"
CONFIG_FILE = CONFIG_DIR / "config.json"
def _load() -> dict:
if not CONFIG_FILE.exists():
return {"current": None, "corps": {}}
return json.loads(CONFIG_FILE.read_text())
def _save(data: dict) -> None:
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
CONFIG_FILE.write_text(json.dumps(data, indent=2, ensure_ascii=False))
def get_all() -> dict:
return _load()
def get_current_corp_id() -> Optional[str]:
return _load().get("current")
def get_current_corp() -> Optional[dict]:
data = _load()
corp_id = data.get("current")
if not corp_id:
return None
return data["corps"].get(corp_id)
def get_corp(corp_id: str) -> Optional[dict]:
"""按 corp_id 获取指定企业认证信息(不要求是当前企业)。"""
return _load()["corps"].get(corp_id)
def add_corp(corp_id: str, name: str, access_token: str, staff_id: str) -> None:
data = _load()
data["corps"][corp_id] = {"name": name, "access_token": access_token, "staff_id": staff_id}
if not data.get("current"):
data["current"] = corp_id
_save(data)
def use_corp(corp_id: str) -> None:
data = _load()
if corp_id not in data["corps"]:
raise ValueError(f"企业 {corp_id} 不存在,请先用 `ekb auth add` 添加")
data["current"] = corp_id
_save(data)
def remove_corp(corp_id: str) -> None:
data = _load()
data["corps"].pop(corp_id, None)
if data.get("current") == corp_id:
remaining = list(data["corps"].keys())
data["current"] = remaining[0] if remaining else None
_save(data)
-65
View File
@@ -1,65 +0,0 @@
"""统一业务异常体系
所有层(api / service / server / commands)统一使用此模块的异常类。
- CLI 层:捕获 EkbError,用 rich 红字输出并 Exit(1)
- Server 层:捕获 EkbError,转换为对应 HTTP 状态码的 JSON 响应
- API 层:捕获 httpx 错误,转换为 AuthenticationError / ApiResponseError
"""
class EkbError(Exception):
"""所有业务异常的基类"""
def __init__(self, message: str, code: int = -1):
self.message = message
self.code = code
super().__init__(message)
class NotLoggedInError(EkbError):
"""未登录/未配置认证。
可传入自定义 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):
"""认证失败:token 过期或无效(HTTP 401)"""
def __init__(self, message: str = "认证已过期,请重新执行 `ekb auth add` 更新 token") -> None:
super().__init__(message, code=401)
class NotFoundError(EkbError):
"""目标资源不存在(HTTP 404)"""
def __init__(self, resource: str, ref: str) -> None:
super().__init__(f"{resource} 不存在:{ref}", code=404)
class ConflictError(EkbError):
"""资源冲突,例如名称重复(HTTP 409)"""
def __init__(self, message: str) -> None:
super().__init__(message, code=409)
class InputError(EkbError):
"""参数/输入校验失败(HTTP 422)"""
def __init__(self, message: str) -> None:
super().__init__(message, code=422)
class ApiResponseError(EkbError):
"""快报 API 返回非 0 业务码"""
def __init__(self, api_code: int, msg: str) -> None:
super().__init__(f"快报 API 错误 [{api_code}]: {msg}", code=api_code)
-47
View File
@@ -1,47 +0,0 @@
# 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`
-56
View File
@@ -1,56 +0,0 @@
"""FastAPI 应用工厂
create_app() 创建并返回完整配置的 FastAPI 实例:
- 注册 auth / agent / rule / sealai 四个路由组
- 统一 EkbError 异常处理(转 HTTP 状态码 + JSON 响应)
"""
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from ekb_cli.errors import EkbError
def create_app() -> FastAPI:
"""创建 FastAPI 应用实例"""
app = FastAPI(
title="ekb-cli API Server",
description=(
"快报(ekuaibao)命令行工具的 HTTP 中转站。\n\n"
"与 `ekb` CLI 共享同一套 service 层逻辑,接口和命令一一对应。\n\n"
"认证信息从 `~/.config/ekb-cli/config.json` 读取,"
"启动前请确保已执行 `ekb auth add`。"
),
version="0.1.0",
)
# ── 注册路由 ──────────────────────────────────────────────
from ekb_cli.server.auth_router import router as auth_router
from ekb_cli.server.agent_router import router as agent_router
from ekb_cli.server.rule_router import router as rule_router
from ekb_cli.server.sealai_router import router as sealai_router
from ekb_cli.server.platform_router import router as platform_router
app.include_router(auth_router, prefix="/auth", tags=["auth"])
app.include_router(agent_router, prefix="/agents", tags=["agent"])
app.include_router(rule_router, prefix="/rules", tags=["rule"])
app.include_router(sealai_router, prefix="/sealai", tags=["sealai"])
app.include_router(platform_router, prefix="/platforms", tags=["platform"])
# ── 统一异常处理:EkbError → HTTP JSON ──────────────────
# code → HTTP status 的映射表
_STATUS_MAP = {401: 401, 404: 404, 409: 409, 422: 422}
@app.exception_handler(EkbError)
async def ekb_error_handler(request: Request, exc: EkbError) -> JSONResponse:
status = _STATUS_MAP.get(exc.code, 500)
return JSONResponse(
status_code=status,
content={"success": False, "error": exc.message, "code": exc.code},
)
@app.get("/", include_in_schema=False)
async def root():
return {"service": "ekb-cli API Server", "docs": "/docs"}
return app
-87
View File
@@ -1,87 +0,0 @@
"""Server:Agent 路由
对应 CLI 命令:
ekb agent list → GET /agents
ekb agent get <id> → GET /agents/{agent_id}
ekb agent create → POST /agents
ekb agent copy <id> → POST /agents/{agent_id}/copy
ekb agent update <id> → PATCH /agents/{agent_id}
ekb agent delete <id> → DELETE /agents/{agent_id}
高阶接口(CLI 暂无对应命令):
GET /agents/dedup-rules → 所有 Agent 关联规则去重列表
"""
from fastapi import APIRouter
from ekb_cli.server.deps import ClientDep
from ekb_cli.services import (
list_agents,
get_agent,
create_agent,
copy_agent,
update_agent,
delete_agent,
get_dedup_rules_across_agents,
AgentCreateInput,
AgentUpdateInput,
)
from ekb_cli.api.schemas import AgentCreateRequest, AgentUpdateRequest
router = APIRouter()
@router.get("", summary="列出所有 Agent")
def route_list_agents(client: ClientDep):
page = list_agents(client)
return {"total": page.totalItems, "items": [item.model_dump() for item in page.items]}
@router.get("/dedup-rules", summary="获取所有 Agent 关联的去重规则")
def route_dedup_rules(client: ClientDep):
"""遍历所有 Agent,汇总其关联规则并去重(按首次出现顺序)"""
rules = get_dedup_rules_across_agents(client)
return {"total": len(rules), "items": [r.model_dump() for r in rules]}
@router.get("/{agent_id}", summary="获取 Agent 详情")
def route_get_agent(agent_id: str, client: ClientDep):
return get_agent(client, agent_id).model_dump()
@router.post("", summary="新建 Agent")
def route_create_agent(body: AgentCreateRequest, client: ClientDep):
inp = AgentCreateInput(
name=body.name,
description=body.description,
mode=body.mode,
sampling_rate=body.sampling_rate,
agree_terms=body.agree_terms,
reject_terms=body.reject_terms,
exempt_terms=body.exempt_terms,
review_terms=body.review_terms,
rule_ids=body.rule_ids,
icon=body.icon,
)
return create_agent(client, inp).model_dump()
@router.post("/{agent_id}/copy", summary="复制 Agent")
def route_copy_agent(agent_id: str, client: ClientDep):
src, new = copy_agent(client, agent_id)
return {"source": src.model_dump(), "copy": new.model_dump()}
@router.patch("/{agent_id}", summary="更新 Agent(patch 式)")
def route_update_agent(agent_id: str, body: AgentUpdateRequest, client: ClientDep):
inp = AgentUpdateInput(
agent_id=agent_id,
**body.model_dump(exclude_unset=True),
)
return update_agent(client, inp).model_dump()
@router.delete("/{agent_id}", summary="删除 Agent")
def route_delete_agent(agent_id: str, client: ClientDep):
detail = delete_agent(client, agent_id)
return {"success": True, "deleted": detail.model_dump()}
-54
View File
@@ -1,54 +0,0 @@
"""Server:Auth 路由
对应 CLI 命令:
ekb auth list → GET /auth/corps
ekb auth add → POST /auth/corps
ekb auth use → PUT /auth/corps/{corp_id}/use
ekb auth remove → DELETE /auth/corps/{corp_id}
ekb auth whoami → GET /auth/whoami
注意:auth 接口不需要 EkbClient(操作本地配置文件),
因此不注入 ClientDep。
"""
from fastapi import APIRouter
from ekb_cli.services import auth_service
from ekb_cli.api.schemas import CorpAddRequest, CorpInfoResponse
router = APIRouter()
@router.get("/corps", response_model=list[CorpInfoResponse], summary="列出所有已配置的企业")
def list_corps():
corps = auth_service.list_corps()
return [CorpInfoResponse(corp_id=c.corp_id, name=c.name, is_current=c.is_current) for c in corps]
@router.post("/corps", response_model=CorpInfoResponse, summary="添加企业认证")
def add_corp(body: CorpAddRequest):
corp = auth_service.add_corp(
corp_id=body.corp_id,
name=body.name,
access_token=body.access_token,
staff_id=body.staff_id,
)
return CorpInfoResponse(corp_id=corp.corp_id, name=corp.name, is_current=corp.is_current)
@router.put("/corps/{corp_id}/use", response_model=CorpInfoResponse, summary="切换当前企业")
def use_corp(corp_id: str):
corp = auth_service.use_corp(corp_id)
return CorpInfoResponse(corp_id=corp.corp_id, name=corp.name, is_current=corp.is_current)
@router.delete("/corps/{corp_id}", summary="删除企业认证")
def remove_corp(corp_id: str):
auth_service.remove_corp(corp_id)
return {"success": True, "corp_id": corp_id}
@router.get("/whoami", response_model=CorpInfoResponse, summary="查看当前企业")
def whoami():
corp = auth_service.whoami()
return CorpInfoResponse(corp_id=corp.corp_id, name=corp.name, is_current=corp.is_current)
-41
View File
@@ -1,41 +0,0 @@
"""FastAPI 依赖注入:获取已认证的 EkbClient / EasoClient
用法:
from ekb_cli.server.deps import ClientDep, EasoClientDep
@router.get("/foo")
def my_route(client: ClientDep): ...
@router.get("/workflow")
def my_workflow_route(client: EasoClientDep): ...
"""
from typing import Annotated, Generator
from fastapi import Depends
from ekb_cli.api import EkbClient, get_client
from ekb_cli.api.platform.easo_client import EasoClient, get_easo_client
def _get_ekb_client() -> Generator[EkbClient, None, None]:
"""FastAPI 依赖:获取快报 HTTP 客户端,请求结束后自动关闭连接"""
client = get_client() # 未登录时抛出 NotLoggedInError → 被全局 handler 捕获
try:
yield client
finally:
client.close()
def _get_easo_client() -> Generator[EasoClient, None, None]:
"""FastAPI 依赖:获取 EASO 工作流客户端(Bearer JWT),请求结束后自动关闭连接"""
client = get_easo_client()
try:
yield client
finally:
client.close()
# 类型别名,路由函数用 `client: ClientDep` 即可,简洁且支持类型推断
ClientDep = Annotated[EkbClient, Depends(_get_ekb_client)]
EasoClientDep = Annotated[EasoClient, Depends(_get_easo_client)]
-108
View File
@@ -1,108 +0,0 @@
"""Server:Platform 路由
对应 CLI 命令:
ekb platform list → GET /platforms
ekb platform workflow-list <platform_id> → GET /platforms/{platform_id}/workflows
ekb platform workflow-get <platform_id> <wf_id> → GET /platforms/{platform_id}/workflows/{wf_id}
ekb platform workflow-stats <platform_id> → GET /platforms/{platform_id}/workflows/stats
ekb platform workflow-charge → GET /platforms/workflows/charge
设计约定:
- 自建应用列表使用 EkbClient(主站认证)
- 工作流列表/统计/配额使用 EasoClient(EASO realm token)
- 工作流详情使用 PiperClient(EASO JWT + platformid Header)
"""
from fastapi import APIRouter, Query
from ekb_cli.server.deps import ClientDep, EasoClientDep
from ekb_cli.api.platform.piper_client import get_piper_client
from ekb_cli.services.platform import (
list_platforms,
list_workflows,
get_workflow,
get_workflow_stats,
get_workflow_charge,
list_all_workflows,
find_workflows_by_task_type,
)
router = APIRouter()
@router.get("", summary="列出所有自建应用")
def route_list_platforms(client: ClientDep):
"""返回当前企业下所有启用的自建应用列表"""
platforms = list_platforms(client)
return {"total": len(platforms), "items": [p.model_dump() for p in platforms]}
@router.get("/workflows/charge", summary="企业工作流资源包配额")
def route_workflow_charge(client: EasoClientDep):
"""获取企业工作流资源包总量/已用/剩余"""
return get_workflow_charge(client).model_dump()
@router.get("/workflows", summary="跨所有应用汇总工作流列表")
def route_list_all_workflows(
ekb_client: ClientDep,
easo_client: EasoClientDep,
enabled_only: bool = Query(True, description="只返回启用状态的工作流"),
task_type: str = Query(None, description="按节点类型过滤,如 http / stop"),
):
"""聚合所有自建应用下的工作流;可选按节点类型过滤"""
if task_type:
matches = find_workflows_by_task_type(easo_client, ekb_client, task_type, enabled_only=enabled_only)
return {
"total": len(matches),
"task_type": task_type,
"items": [
{
"platform_id": m.platform_id,
"platform_name": m.platform_name,
"workflow_id": m.workflow_id,
"workflow_name": m.workflow_name,
"matched_task_count": len(m.matched_tasks),
"matched_tasks": m.matched_tasks,
}
for m in matches
],
}
items = list_all_workflows(easo_client, ekb_client, enabled_only=enabled_only)
return {
"total": len(items),
"items": [
{
"platform_id": i.platform_id,
"platform_name": i.platform_name,
**i.workflow.model_dump(),
}
for i in items
],
}
@router.get("/{platform_id}/workflows/stats", summary="工作流执行统计")
def route_workflow_stats(platform_id: str, client: EasoClientDep):
"""获取指定自建应用的工作流执行统计(总数/成功/失败等)"""
return get_workflow_stats(client, platform_id).model_dump()
@router.get("/{platform_id}/workflows/{pipeline_id}", summary="工作流完整配置(节点列表)")
def route_get_workflow(platform_id: str, pipeline_id: str):
"""获取指定工作流的完整配置,包含所有节点及其参数"""
with get_piper_client(platform_id) as client:
result = get_workflow(client, pipeline_id)
return result.model_dump()
@router.get("/{platform_id}/workflows", summary="列出指定应用的工作流")
def route_list_workflows(
platform_id: str,
client: EasoClientDep,
page: int = Query(1, ge=1, description="页码,从 1 开始"),
page_size: int = Query(20, ge=1, le=100, description="每页数量"),
):
"""分页获取指定自建应用下的工作流列表"""
result = list_workflows(client, platform_id, page=page, page_size=page_size)
return result.model_dump()
-57
View File
@@ -1,57 +0,0 @@
"""Server:Rule 路由
对应 CLI 命令:
ekb agent rules → GET /rules
ekb agent rule-get <ref> → GET /rules/{rule_ref}
ekb agent rule-create → POST /rules
(暂无 CLI rule-update) → PATCH /rules/{rule_ref}
"""
from typing import Optional
from fastapi import APIRouter, Query
from ekb_cli.server.deps import ClientDep
from ekb_cli.services import list_rules, get_rule, create_rule, update_rule
from ekb_cli.api.schemas import RuleCreateRequest, RuleUpdateRequest
router = APIRouter()
@router.get("", summary="列出所有审核规则")
def route_list_rules(
client: ClientDep,
level: Optional[str] = Query(None, description="按风险等级筛选:严重 / 一般"),
):
page, items = list_rules(client, level=level)
return {
"total": page.totalItems,
"filtered": len(items),
"items": [r.model_dump() for r in items],
}
@router.get("/{rule_ref}", summary="获取单条规则详情(支持 ID 或编码)")
def route_get_rule(rule_ref: str, client: ClientDep):
"""
rule_ref 支持:
- 完整 ID(长字符串)
- 编码数字,如 "1" / "0001" / "#0001"
"""
return get_rule(client, rule_ref).model_dump()
@router.post("", summary="新建审核规则")
def route_create_rule(body: RuleCreateRequest, client: ClientDep):
return create_rule(client, body.purpose, body.description, body.level).model_dump()
@router.patch("/{rule_ref}", summary="更新审核规则(patch 式)")
def route_update_rule(rule_ref: str, body: RuleUpdateRequest, client: ClientDep):
return update_rule(
client,
rule_ref=rule_ref,
purpose=body.purpose,
description=body.description,
level=body.level,
).model_dump()
-276
View File
@@ -1,276 +0,0 @@
"""Server:SealAI 路由
对应 CLI 命令:
ekb sealai whoami → GET /sealai/me
ekb sealai billing → GET /sealai/billing
ekb sealai rules → GET /sealai/rules
ekb sealai rule-create → POST /sealai/rules
ekb sealai rule-update → PUT /sealai/rules/{rule_id}
ekb sealai rule-delete → DELETE /sealai/rules/{rule_id}
ekb sealai versions → GET /sealai/rule-set-versions
—(Server 专属)— → GET /sealai/preference
—(Server 专属)— → POST /sealai/preference
—(Server 专属)— → PATCH /sealai/preference/decision
—(Server 专属)— → GET /sealai/knowledge/articles
—(Server 专属)— → POST /sealai/knowledge/articles
—(Server 专属)— → GET /sealai/knowledge/articles/{article_id}
—(Server 专属)— → PATCH /sealai/knowledge/articles/{article_id}
设计约定:
- 路由函数不持有 SealAiClient,统一由 services.sealai 层管理(缓存、关闭、401 恢复)
- 路由函数只做参数绑定 + 调用 service 函数,返回值直接交给 FastAPI 序列化
"""
from typing import Optional
from fastapi import APIRouter, Query
from ekb_cli.services.sealai import (
get_whoami,
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,
)
from ekb_cli.api.sealai.schemas import (
MeData,
BillingStatusData,
DraftRule,
DraftRulesData,
RuleSetVersion,
PublishVersionData,
AiApprovalConfig,
AiApprovalSaveResult,
KnowledgeArticle,
KnowledgeArticleListData,
# Server 请求模型
RuleCreateRequest,
RuleUpdateRequest,
PublishVersionRequest,
DecisionPreferencesUpdateRequest,
ArticleCreateRequest,
ArticleUpdateRequest,
)
router = APIRouter()
# ── 认证 / 计费 ────────────────────────────────────────────────────────────────
@router.get("/me", response_model=MeData, summary="查看当前 SealAI 用户身份及租户信息")
def sealai_whoami(
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
refresh: bool = Query(False, description="强制刷新 Bearer token"),
):
return get_whoami(corp_id=corp_id, force_refresh=refresh)
@router.get("/billing", response_model=BillingStatusData, summary="查看 SealAI 订阅状态及功能配额")
def sealai_billing(
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return query_billing_status(corp_id=corp_id)
# ── 审核规则(草稿区) ─────────────────────────────────────────────────────────
@router.get("/rules", response_model=DraftRulesData, summary="查看草稿区审核规则列表")
def sealai_list_rules(
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return get_draft_rules(corp_id=corp_id)
@router.post("/rules", response_model=DraftRule, summary="新建草稿审核规则")
def sealai_create_rule(
body: RuleCreateRequest,
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return add_draft_rule(
corp_id=corp_id,
description=body.description,
scope=body.scope,
strictness=body.strictness,
)
@router.put("/rules/{rule_id}", response_model=DraftRule, summary="更新草稿审核规则(partial)")
def sealai_update_rule(
rule_id: str,
body: RuleUpdateRequest,
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return edit_draft_rule(
corp_id=corp_id, rule_id=rule_id,
description=body.description,
scope=body.scope,
strictness=body.strictness,
)
@router.delete("/rules/{rule_id}", summary="删除草稿审核规则")
def sealai_delete_rule(
rule_id: str,
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
remove_draft_rule(corp_id=corp_id, rule_id=rule_id)
return {"success": True, "rule_id": rule_id}
# ── 已发布版本历史 ─────────────────────────────────────────────────────────────
@router.get(
"/rule-set-versions",
response_model=list[RuleSetVersion],
summary="查看已发布规则集版本历史",
)
def sealai_list_versions(
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return get_published_versions(corp_id=corp_id)
@router.post(
"/rule-set-versions/publish",
response_model=PublishVersionData,
summary="发布当前草稿规则为新版本",
)
def sealai_publish_version(
body: PublishVersionRequest,
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return publish_draft_rules(corp_id=corp_id, version_name=body.version_name)
# ── 风格偏好(AI 审批配置) ─────────────────────────────────────────────────────
@router.get(
"/preference",
response_model=AiApprovalConfig,
summary="查看 AI 审批风格偏好配置(决策偏好 + 集成系统信息)",
)
def sealai_get_preference(
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return get_preference(corp_id=corp_id)
@router.post(
"/preference",
response_model=AiApprovalSaveResult,
summary="整体替换 AI 审批配置(需传完整配置对象)",
)
def sealai_save_preference(
body: AiApprovalConfig,
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return save_preference(corp_id=corp_id, config=body)
@router.patch(
"/preference/decision",
response_model=AiApprovalSaveResult,
summary="Patch 式更新决策偏好(只传需要改动的字段,其余保持不变)",
)
def sealai_patch_decision_preferences(
body: DecisionPreferencesUpdateRequest,
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return update_decision_preferences(
corp_id=corp_id,
explicit_approve=body.explicit_approve,
explicit_reject=body.explicit_reject,
exempt_approve=body.exempt_approve,
review=body.review,
)
# ── 知识文档 ───────────────────────────────────────────────────────────────────
@router.get(
"/knowledge/articles",
response_model=KnowledgeArticleListData,
summary="查询知识文档列表(支持场景过滤、分页、排序)",
)
def sealai_list_articles(
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
scenarios: Optional[list[str]] = Query(None, description="场景过滤,可选 audit / fill"),
offset: int = Query(0, description="分页偏移量"),
limit: int = Query(20, description="每页数量(最大建议 100)"),
sort_by: str = Query("createdAt", description="排序字段"),
sort_order: str = Query("desc", description="排序方向:asc | desc"),
):
return get_articles(
corp_id=corp_id,
scenarios=scenarios,
offset=offset,
limit=limit,
sort_by=sort_by,
sort_order=sort_order,
)
@router.post(
"/knowledge/articles",
response_model=KnowledgeArticle,
summary="新建知识文档",
)
def sealai_create_article(
body: ArticleCreateRequest,
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return add_article(
corp_id=corp_id,
title=body.title,
purpose=body.purpose,
content=body.content,
content_type=body.content_type,
status=body.status,
scenarios=body.scenarios,
tags=body.tags,
)
@router.get(
"/knowledge/articles/{article_id}",
response_model=KnowledgeArticle,
summary="查看知识文档详情",
)
def sealai_get_article(
article_id: str,
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return get_article_detail(corp_id=corp_id, article_id=article_id)
@router.patch(
"/knowledge/articles/{article_id}",
response_model=KnowledgeArticle,
summary="更新知识文档(只传需要改动的字段)",
)
def sealai_update_article(
article_id: str,
body: ArticleUpdateRequest,
corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"),
):
return edit_article(
corp_id=corp_id,
article_id=article_id,
title=body.title,
purpose=body.purpose,
content=body.content,
content_type=body.content_type,
status=body.status,
enabled=body.enabled,
scenarios=body.scenarios,
tags=body.tags,
)
-56
View File
@@ -1,56 +0,0 @@
# 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)` |
-88
View File
@@ -1,88 +0,0 @@
"""Service 层统一 re-export
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
CorpInfo,
CorpDetail,
list_corps,
whoami,
add_corp,
use_corp,
remove_corp,
)
from ekb_cli.services.agent_service import ( # noqa: F401
AgentCreateInput,
AgentUpdateInput,
MODE_NAMES,
MODE_DISPLAY,
DEFAULT_ICON,
list_agents,
get_agent,
create_agent,
copy_agent,
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,
list_rules,
get_rule,
create_rule,
update_rule,
# CLI 便捷函数(自管 client 生命周期,commands/* 层使用)
list_rules_cmd,
get_rule_cmd,
create_rule_cmd,
)
from ekb_cli.services.platform import ( # noqa: F401
list_platforms,
list_platforms_cmd,
# 工作流
list_workflows,
get_workflow_stats,
get_workflow_charge,
list_workflows_cmd,
get_workflow_stats_cmd,
get_workflow_charge_cmd,
)
# 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_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,
)
-263
View File
@@ -1,263 +0,0 @@
"""Service 层:Agent 业务逻辑
将原本散落在 commands/agent/*.py 中的编排逻辑集中到此处。
CLI 和 Server 共用同一套逻辑,只有输出格式不同。
职责:
- 参数校验(mode 合法性、samplingRate 范围)
- 多步编排(check_name → save、get → merge → save)
- 高阶组合查询(获取所有 Agent 关联的去重规则)
- 统一抛出 EkbError 子类,不关心上层如何渲染
"""
from dataclasses import dataclass, field
from typing import Optional
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,
get_agent as api_get_agent,
save_agent as api_save_agent,
delete_agent as api_delete_agent,
)
from ekb_cli.api.schemas import AgentDetail, AgentSummary, AgentRuleRef, PageData
from ekb_cli.errors import NotFoundError, ConflictError, InputError
# ── 枚举常量 ─────────────────────────────────────────────────
#: 前端传入的模式字符串 → 快报 API 的 int 值
MODE_NAMES: dict[str, int] = {"auto": 0, "semi": 1, "assist": 2}
#: 快报 API int 值 → 可读中文
MODE_DISPLAY: dict[int, str] = {0: "全自动", 1: "半自动", 2: "辅助"}
DEFAULT_ICON = "https://statics.ekuaibao.com/eui/eui-static/male5.png"
# ── 输入数据类 ───────────────────────────────────────────────
@dataclass
class AgentCreateInput:
"""新建 Agent 的输入参数"""
name: str
description: str = ""
mode: str = "assist" # "auto" / "semi" / "assist"
sampling_rate: int = 0
agree_terms: str = ""
reject_terms: str = ""
exempt_terms: str = ""
review_terms: str = ""
rule_ids: list[str] = field(default_factory=list)
icon: str = DEFAULT_ICON
@dataclass
class AgentUpdateInput:
"""更新 Agent 的输入参数(所有字段可选,None 表示不修改)"""
agent_id: str
name: Optional[str] = None
description: Optional[str] = None
mode: Optional[str] = None # "auto" / "semi" / "assist"
sampling_rate: Optional[int] = None
state: Optional[int] = None
agree_terms: Optional[str] = None
reject_terms: Optional[str] = None
exempt_terms: Optional[str] = None
review_terms: Optional[str] = None
# ── 查询 ─────────────────────────────────────────────────────
def list_agents(client: EkbClient) -> PageData[AgentSummary]:
"""列出所有 Agent(分页,默认 size=1000 拉全量)"""
return api_list_agents(client)
def get_agent(client: EkbClient, agent_id: str) -> AgentDetail:
"""获取 Agent 详情,不存在时抛出 NotFoundError"""
detail = api_get_agent(client, agent_id)
if not detail:
raise NotFoundError("Agent", agent_id)
return detail
# ── 创建 ─────────────────────────────────────────────────────
def create_agent(client: EkbClient, inp: AgentCreateInput) -> AgentDetail:
"""新建 Agent
校验:
- mode 必须是 auto / semi / assist
- 名称不能与已有 Agent 重复
"""
if inp.mode not in MODE_NAMES:
raise InputError(f"mode 必须是 auto / semi / assist,当前:{inp.mode}")
if not api_check_name(client, inp.name):
raise ConflictError(f"名称「{inp.name}」已存在,请换一个")
payload = {
"icon": inp.icon,
"name": inp.name,
"description": inp.description,
"mode": MODE_NAMES[inp.mode],
"agreeTerms": inp.agree_terms,
"rejectTerms": inp.reject_terms,
"exemptTerms": inp.exempt_terms,
"reviewTerms": inp.review_terms,
"state": 1,
"ruleIds": inp.rule_ids,
}
return api_save_agent(client, payload)
# ── 复制 ─────────────────────────────────────────────────────
def copy_agent(client: EkbClient, agent_id: str) -> tuple[AgentDetail, AgentDetail]:
"""复制 Agent,新 Agent 名称自动追加「(副本)」
Returns:
(源 Agent, 新 Agent)
"""
src = get_agent(client, agent_id) # 不存在会抛 NotFoundError
new_name = src.name + "(副本)"
if not api_check_name(client, new_name):
raise ConflictError(f"名称「{new_name}」已存在,无法复制")
payload = {
"icon": src.icon,
"name": new_name,
"description": src.description,
"mode": src.mode,
"agreeTerms": src.agreeTerms,
"rejectTerms": src.rejectTerms,
"exemptTerms": src.exemptTerms,
"reviewTerms": src.reviewTerms,
"state": 1,
"ruleIds": [r.id for r in src.agentRule],
}
# 半自动模式需带上抽检比例
if src.mode == 1:
payload["samplingRate"] = src.samplingRate
new = api_save_agent(client, payload)
return src, new
# ── 更新 ─────────────────────────────────────────────────────
def update_agent(client: EkbClient, inp: AgentUpdateInput) -> AgentDetail:
"""更新 Agent(patch 式:只改传入字段,其余保持原值)
校验:
- mode 若传入必须是 auto / semi / assist
- sampling_rate 若传入必须在 0-100
"""
if inp.mode is not None and inp.mode not in MODE_NAMES:
raise InputError(f"mode 必须是 auto / semi / assist,当前:{inp.mode}")
if inp.sampling_rate is not None and not (0 <= inp.sampling_rate <= 100):
raise InputError("sampling-rate 范围是 0-100")
# 先拉原始数据,再 merge
d = get_agent(client, inp.agent_id)
mode_val = MODE_NAMES[inp.mode] if inp.mode is not None else d.mode
payload: dict = {
"id": d.id,
"icon": d.icon,
"name": inp.name if inp.name is not None else d.name,
"description": inp.description if inp.description is not None else d.description,
"mode": mode_val,
"agreeTerms": inp.agree_terms if inp.agree_terms is not None else d.agreeTerms,
"rejectTerms": inp.reject_terms if inp.reject_terms is not None else d.rejectTerms,
"exemptTerms": inp.exempt_terms if inp.exempt_terms is not None else d.exemptTerms,
"reviewTerms": inp.review_terms if inp.review_terms is not None else d.reviewTerms,
"state": inp.state if inp.state is not None else d.state,
"ruleIds": [r.id for r in d.agentRule],
}
if mode_val == 1:
payload["samplingRate"] = (
inp.sampling_rate if inp.sampling_rate is not None else d.samplingRate
)
return api_save_agent(client, payload)
# ── 删除 ─────────────────────────────────────────────────────
def delete_agent(client: EkbClient, agent_id: str) -> AgentDetail:
"""删除 Agent(软删除:state=2),返回被删除的 Agent 用于确认展示"""
detail = get_agent(client, agent_id)
api_delete_agent(client, agent_id)
return detail
# ── 高阶组合接口 ─────────────────────────────────────────────
def get_dedup_rules_across_agents(client: EkbClient) -> list[AgentRuleRef]:
"""遍历所有 Agent,收集其关联规则并去重
用途:统计企业内实际被引用的规则集合。
Returns:
去重后的规则列表(保持首次出现的顺序)
"""
page = api_list_agents(client)
seen: set[str] = set()
rules: list[AgentRuleRef] = []
for summary in page.items:
detail = api_get_agent(client, summary.id)
for r in detail.agentRule:
if r.id not in seen:
seen.add(r.id)
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)
-81
View File
@@ -1,81 +0,0 @@
"""Service 层:认证/企业配置管理
职责:封装 config 模块的数据操作,向上提供类型化返回值。
CLI 和 Server 都调用此层,不直接操作 config。
注意:auth add 的交互式输入逻辑(prompt)留在 CLI 层,
此层只处理数据写入,不涉及 I/O。
"""
from dataclasses import dataclass
from typing import Optional
from ekb_cli import config
from ekb_cli.errors import NotFoundError, NotLoggedInError
# ── 数据类 ────────────────────────────────────────────────────
@dataclass
class CorpInfo:
"""企业信息(不含敏感 token,用于展示和返回)"""
corp_id: str
name: str
is_current: bool
@dataclass
class CorpDetail:
"""企业完整信息(含 token,用于内部传递)"""
corp_id: str
name: str
access_token: str
staff_id: str
is_current: bool
# ── 查询 ──────────────────────────────────────────────────────
def list_corps() -> list[CorpInfo]:
"""列出所有已配置的企业"""
data = config.get_all()
current = data.get("current")
return [
CorpInfo(corp_id=cid, name=info["name"], is_current=(cid == current))
for cid, info in data.get("corps", {}).items()
]
def whoami() -> CorpInfo:
"""获取当前企业信息,未登录时抛出 NotLoggedInError"""
corp = config.get_current_corp()
corp_id = config.get_current_corp_id()
if not corp or not corp_id:
raise NotLoggedInError()
current = config.get_current_corp_id()
return CorpInfo(corp_id=corp_id, name=corp["name"], is_current=(corp_id == current))
# ── 写操作 ────────────────────────────────────────────────────
def add_corp(corp_id: str, name: str, access_token: str, staff_id: str) -> CorpInfo:
"""添加企业认证,返回添加后的企业信息"""
config.add_corp(corp_id=corp_id, name=name, access_token=access_token, staff_id=staff_id)
current = config.get_current_corp_id()
return CorpInfo(corp_id=corp_id, name=name, is_current=(current == corp_id))
def use_corp(corp_id: str) -> CorpInfo:
"""切换当前企业,企业不存在时抛出 NotFoundError"""
try:
config.use_corp(corp_id)
except ValueError:
raise NotFoundError("企业", corp_id)
data = config.get_all()
info = data["corps"][corp_id]
return CorpInfo(corp_id=corp_id, name=info["name"], is_current=True)
def remove_corp(corp_id: str) -> None:
"""删除企业认证配置"""
config.remove_corp(corp_id)
@@ -1,22 +0,0 @@
# services/platform — 自建应用域服务层
## 已实现
| 文件 | 说明 |
|---|---|
| `__init__.py` | 自建应用列表(`list_platforms` / `list_platforms_cmd`) |
| `workflow_service.py` | 工作流列表 / 统计 / 配额(`list_workflows` / `get_workflow_stats` / `get_workflow_charge` 及对应 `_cmd`) |
## 待实现(预留)
以下模块服务层尚未开发,待接口确认后按需补充:
| 文件(待建) | 对应业务 | 依赖 API |
|---|---|---|
| `entity_service.py` | 业务对象(实体/数据表)CRUD | `api/platform/entity_api.py`(待建) |
| `page_service.py` | 页面设计器 | 待抓包 |
| `card_service.py` | 互联卡片 | 待抓包 |
| `variable_service.py` | 应用变量 | 待抓包 |
| `log_service.py` | 应用日志 | `api/easo/pipelines/logs`(运行日志参数) |
新增服务时,在本目录创建对应 `xxx_service.py`,并在 `__init__.py` 和父级 `services/__init__.py` 补充 re-export。
-49
View File
@@ -1,49 +0,0 @@
"""Service 层:自建应用(DataLink Platform)业务逻辑
职责:
- 列出当前企业下所有启用的自建应用
- 统一抛出 EkbError 子类,不关心上层如何渲染
"""
from typing import List
from ekb_cli.api import EkbClient, get_client
from ekb_cli.api.platform.schemas import Platform
from ekb_cli.api.platform.platform_api import list_platforms as api_list_platforms
# ── 查询 ─────────────────────────────────────────────────────
def list_platforms(client: EkbClient) -> List[Platform]:
"""列出所有启用的自建应用"""
return api_list_platforms(client)
# ── CLI 便捷函数(自管 client 生命周期)────────────────────────
# commands/* 层调用这批函数,不需要自行 import get_client,
# 保持 commands → services → api 的依赖方向。
def list_platforms_cmd() -> List[Platform]:
"""CLI 便捷函数:自动获取当前企业 client 并列出所有自建应用"""
with get_client() as client:
return list_platforms(client)
# ── 工作流子模块 re-export ────────────────────────────────────
from ekb_cli.services.platform.workflow_service import ( # noqa: F401, E402
list_workflows,
get_workflow,
get_workflow_stats,
get_workflow_charge,
list_all_workflows,
find_workflows_by_task_type,
WorkflowWithPlatform,
WorkflowTaskMatch,
list_workflows_cmd,
get_workflow_cmd,
get_workflow_stats_cmd,
get_workflow_charge_cmd,
list_all_workflows_cmd,
find_workflows_by_task_type_cmd,
)
@@ -1,195 +0,0 @@
"""Service 层:工作流(EASO Pipeline)业务逻辑
域:
- unity.ekuaibao.com(EasoClient):列表 / 统计 / 配额
- piper.ekuaibao.com(PiperClient):工作流配置详情
职责:
- 分页列出指定自建应用下的工作流
- 获取单个工作流完整配置(节点列表)
- 查询工作流执行统计
- 查询企业工作流配额
- 跨应用聚合查询(按节点类型过滤)
- 统一抛出 EkbError 子类,不关心上层如何渲染
"""
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from ekb_cli.api import get_client
from ekb_cli.api.platform.easo_client import EasoClient, get_easo_client
from ekb_cli.api.platform.piper_client import PiperClient, get_piper_client
from ekb_cli.api.platform.platform_api import list_platforms as api_list_platforms
from ekb_cli.api.platform.schemas import (
Platform,
Workflow,
WorkflowPage,
WorkflowStats,
WorkflowCharge,
WorkflowDetail,
)
from ekb_cli.api.platform.workflow_api import (
list_workflows as api_list_workflows,
get_workflow as api_get_workflow,
get_workflow_stats as api_get_workflow_stats,
get_workflow_charge as api_get_workflow_charge,
)
# ── 查询 ─────────────────────────────────────────────────────
def list_workflows(
client: EasoClient,
platform_id: str,
page: int = 1,
page_size: int = 20,
) -> WorkflowPage:
"""列出指定自建应用下的工作流(分页)"""
return api_list_workflows(client, platform_id, page, page_size)
def get_workflow(client: PiperClient, pipeline_id: str) -> WorkflowDetail:
"""获取单个工作流的完整配置(包含所有节点及参数)"""
return api_get_workflow(client, pipeline_id)
def get_workflow_stats(client: EasoClient, platform_id: str) -> WorkflowStats:
"""获取指定自建应用的工作流执行统计"""
return api_get_workflow_stats(client, platform_id)
def get_workflow_charge(client: EasoClient) -> WorkflowCharge:
"""获取企业工作流资源包/配额"""
return api_get_workflow_charge(client)
# ── 跨应用聚合 ────────────────────────────────────────────────
@dataclass
class WorkflowWithPlatform:
"""携带所属自建应用信息的工作流摘要"""
platform_id: str
platform_name: str
workflow: Workflow
@dataclass
class WorkflowTaskMatch:
"""在工作流中匹配到的节点"""
platform_id: str
platform_name: str
workflow_id: str
workflow_name: str
matched_tasks: List[Dict[str, Any]] = field(default_factory=list)
def _collect_tasks_by_type(tasks: list, task_type: Optional[str]) -> List[Dict[str, Any]]:
"""递归收集所有层级中匹配类型的节点(含控制节点内的嵌套节点)。
task_type 为 None 时收集全部节点。
"""
result = []
for t in tasks:
t_type = t.get("type") if isinstance(t, dict) else getattr(t, "type", "")
if task_type is None or t_type == task_type:
result.append(t if isinstance(t, dict) else t.model_dump())
nested = t.get("tasks") if isinstance(t, dict) else getattr(t, "tasks", None)
if nested and isinstance(nested, list):
result.extend(_collect_tasks_by_type(nested, task_type))
return result
def list_all_workflows(
easo_client: EasoClient,
ekb_client,
enabled_only: bool = True,
) -> List[WorkflowWithPlatform]:
"""聚合所有自建应用下的工作流,返回带平台信息的扁平列表。
enabled_only=True 时只返回 state=1 的工作流。
"""
platforms: List[Platform] = api_list_platforms(ekb_client)
result: List[WorkflowWithPlatform] = []
for p in platforms:
page = api_list_workflows(easo_client, p.id, page=1, page_size=100)
for wf in page.pipelineList:
if enabled_only and wf.state != 1:
continue
result.append(WorkflowWithPlatform(
platform_id=p.id,
platform_name=p.name,
workflow=wf,
))
return result
def find_workflows_by_task_type(
easo_client: EasoClient,
ekb_client,
task_type: str,
enabled_only: bool = True,
) -> List[WorkflowTaskMatch]:
"""跨所有自建应用,找出含指定节点类型的工作流。
递归检查控制节点(every / condition 等)内的嵌套节点。
返回含匹配节点列表的结果,每条记录对应一个工作流。
"""
all_wfs = list_all_workflows(easo_client, ekb_client, enabled_only=enabled_only)
matches: List[WorkflowTaskMatch] = []
for item in all_wfs:
wf = item.workflow
matched = _collect_tasks_by_type(wf.tasks, task_type)
if matched:
matches.append(WorkflowTaskMatch(
platform_id=item.platform_id,
platform_name=item.platform_name,
workflow_id=wf.id,
workflow_name=wf.pipelineName,
matched_tasks=matched,
))
return matches
# ── CLI 便捷函数(自管 client 生命周期)────────────────────────
# commands/* 层调用这批函数,保持 commands → services → api 依赖方向。
def list_workflows_cmd(
platform_id: str,
page: int = 1,
page_size: int = 20,
) -> WorkflowPage:
"""CLI 便捷函数:自动获取 EasoClient 并列出工作流"""
with get_easo_client() as client:
return list_workflows(client, platform_id, page, page_size)
def get_workflow_cmd(platform_id: str, pipeline_id: str) -> WorkflowDetail:
"""CLI 便捷函数:自动获取 PiperClient 并查询工作流完整配置"""
with get_piper_client(platform_id) as client:
return get_workflow(client, pipeline_id)
def get_workflow_stats_cmd(platform_id: str) -> WorkflowStats:
"""CLI 便捷函数:自动获取 EasoClient 并查询工作流统计"""
with get_easo_client() as client:
return get_workflow_stats(client, platform_id)
def get_workflow_charge_cmd() -> WorkflowCharge:
"""CLI 便捷函数:自动获取 EasoClient 并查询工作流配额"""
with get_easo_client() as client:
return get_workflow_charge(client)
def list_all_workflows_cmd(enabled_only: bool = True) -> List[WorkflowWithPlatform]:
"""CLI 便捷函数:跨所有应用汇总工作流"""
with get_client() as ekb_client, get_easo_client() as easo_client:
return list_all_workflows(easo_client, ekb_client, enabled_only=enabled_only)
def find_workflows_by_task_type_cmd(
task_type: str,
enabled_only: bool = True,
) -> List[WorkflowTaskMatch]:
"""CLI 便捷函数:跨所有应用查找含指定节点类型的工作流"""
with get_client() as ekb_client, get_easo_client() as easo_client:
return find_workflows_by_task_type(easo_client, ekb_client, task_type, enabled_only=enabled_only)
-144
View File
@@ -1,144 +0,0 @@
"""Service 层:审核规则(Rule)业务逻辑
将原本散落在 commands/agent/rule_*.py 中的逻辑集中到此处。
CLI 和 Server 共用同一套逻辑。
职责:
- 参数校验(level 合法性)
- 按编码/ID 查找单条规则(快报无直接 get 接口,需拉全量过滤)
- 规则 CRUD 编排
"""
from typing import Optional
from ekb_cli.api import EkbClient, get_client
from ekb_cli.api.rule import (
list_rules as api_list_rules,
save_rule as api_save_rule,
update_rule as api_update_rule,
)
from ekb_cli.api.schemas import PageData, Rule, RuleWithAgents
from ekb_cli.errors import NotFoundError, InputError
# ── 枚举常量 ─────────────────────────────────────────────────
VALID_LEVELS = {"严重", "一般"}
# ── 查询 ─────────────────────────────────────────────────────
def list_rules(
client: EkbClient,
level: Optional[str] = None,
) -> tuple[PageData[RuleWithAgents], list[RuleWithAgents]]:
"""列出所有规则,可按 level 筛选
Returns:
(原始分页数据, 筛选后的 items 列表)
返回原始分页是为了让调用方能拿到 totalItems 等元数据
"""
page = api_list_rules(client)
items = page.items
if level:
items = [r for r in items if r.level == level]
return page, items
def get_rule(client: EkbClient, rule_ref: str) -> RuleWithAgents:
"""按 ID 或编码查找单条规则
rule_ref 支持以下格式:
- 完整 ID(长字符串)
- 编码数字,如 "1" / "0001" / "#0001"
快报无直接的 rule/detail 接口,因此拉全量后客户端过滤。
"""
page = api_list_rules(client)
# 纯数字且不超过 4 位 → 按编码匹配(补零对齐)
stripped = rule_ref.lstrip("#")
if stripped.isdigit() and len(stripped) <= 4:
code = f"#{stripped.zfill(4)}"
rule = next((r for r in page.items if r.code == code), None)
else:
rule = next((r for r in page.items if r.id == rule_ref), None)
if not rule:
raise NotFoundError("规则", rule_ref)
return rule
# ── 创建 ─────────────────────────────────────────────────────
def create_rule(
client: EkbClient,
purpose: str,
description: str,
level: str = "严重",
) -> Rule:
"""新建审核规则
校验:level 必须是 严重 / 一般
"""
if level not in VALID_LEVELS:
raise InputError(f"--level 只接受 严重 / 一般,当前值:{level}")
payload = {"purpose": purpose, "description": description, "level": level}
return api_save_rule(client, payload)
# ── 更新 ─────────────────────────────────────────────────────
def update_rule(
client: EkbClient,
rule_ref: str,
purpose: Optional[str] = None,
description: Optional[str] = None,
level: Optional[str] = None,
) -> Rule:
"""更新审核规则(patch 式)
rule_ref 同 get_rule,支持 ID 或编码。
只传需要修改的字段,其余保持原值。
"""
if level is not None and level not in VALID_LEVELS:
raise InputError(f"--level 只接受 严重 / 一般,当前值:{level}")
current = get_rule(client, rule_ref)
payload = {
"id": current.id,
"code": current.code,
"purpose": purpose if purpose is not None else current.purpose,
"description": description if description is not None else current.description,
"level": level if level is not None else current.level,
}
return api_update_rule(client, payload)
# ── CLI 便捷函数(自管 client 生命周期)────────────────────────
# commands/* 层调用这批函数,不需要自行 import get_client,
# 保持 commands → services → api 的依赖方向。
def list_rules_cmd(
level: Optional[str] = None,
) -> tuple[PageData[RuleWithAgents], list[RuleWithAgents]]:
"""CLI 便捷函数:自动获取当前企业 client 并列出所有规则"""
with get_client() as client:
return list_rules(client, level=level)
def get_rule_cmd(rule_ref: str) -> RuleWithAgents:
"""CLI 便捷函数:自动获取当前企业 client 并查找单条规则"""
with get_client() as client:
return get_rule(client, rule_ref)
def create_rule_cmd(
purpose: str,
description: str,
level: str = "严重",
) -> Rule:
"""CLI 便捷函数:自动获取当前企业 client 并新建规则"""
with get_client() as client:
return create_rule(client, purpose=purpose, description=description, level=level)
@@ -1,72 +0,0 @@
# services/sealai/ — SealAI 子平台业务逻辑层
## 职责边界
SealAI 是独立于快报主站的 Next.js 平台(`{corpId}.sealai.cc`),认证体系完全独立。
本子包封装所有 SealAI 相关业务逻辑,对外隐藏 `api/sealai/` 传输层细节,
**同时隐藏 `SealAiClient` 的创建、缓存与关闭**。
## 模块说明
| 模块 | 职责 |
|---|---|
| `auth_service.py` | SSO token 换取 + 磁盘/内存双层缓存 + `_sealai_call` 统一调用入口(含 401 自动恢复) |
| `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):
{ "ID01Jdq2yIDnMr": { "token": "...", "fetched_at": 1712345678 } }
→ CLI / Server 进程间共享
内存缓存(模块级 _client_cache,TTL 同 token):
{ "corp_id": (SealAiClient, fetched_at_float) }
→ CLI 进程结束自动回收;Server 进程中长期保持,复用 httpx 连接池
```
**401 自动恢复**:`_sealai_call` 捕获 `AuthenticationError` 后,同时清除内存 client
和磁盘 token,强制重新换取,然后单次重试。调用方无需感知这一过程。
## 调用方约定
- `commands/*` 和 `server/*` 只传 `corp_id`,不持有也不传递 `SealAiClient`
- `SealAiClient` 的创建和生命周期完全由 `auth_service` 管理
## 对外接口(统一从 `services.sealai` 导入)
```python
from ekb_cli.services.sealai import (
# 认证(调试 / 外部集成)
get_bearer_token, # 获取 Bearer JWT 字符串
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,
)
```
**不对外暴露**:`get_sealai_client`、`_sealai_call`、`_get_or_create_client`
## 导入约定
```
services/sealai/* → api/sealai/* ✅ 允许
commands/* → api/sealai/* ❌ 禁止(必须通过 services 层)
server/* → api/sealai/* ❌ 禁止(必须通过 services 层)
```
-65
View File
@@ -1,65 +0,0 @@
"""SealAI 服务层统一 re-export。
对外约定
--------
commands/* 和 server/* 只从此处(或 services 顶层)导入,不直接访问子模块。
不再对外暴露 get_sealai_client / _sealai_call 等内部函数:
- SealAiClient 的创建、缓存、关闭、401 恢复全部由 auth_service 内部承担
- 调用方只需传 corp_id,无需感知 client 的存在
"""
from ekb_cli.services.sealai.auth_service import ( # noqa: F401
invalidate_token,
get_bearer_token,
get_whoami,
)
from ekb_cli.services.sealai.billing_service import ( # noqa: F401
query_billing_status,
get_feature_usage,
)
from ekb_cli.services.sealai.rules_service import ( # noqa: F401
get_draft_rules,
add_draft_rule,
edit_draft_rule,
remove_draft_rule,
get_published_versions,
publish_draft_rules,
)
from ekb_cli.services.sealai.preference_service import ( # noqa: F401
get_preference,
update_decision_preferences,
save_preference,
)
from ekb_cli.services.sealai.knowledge_service import ( # noqa: F401
get_articles,
get_article_detail,
add_article,
edit_article,
)
__all__ = [
# 认证(仅保留对外有意义的操作)
"invalidate_token",
"get_bearer_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",
]
-239
View File
@@ -1,239 +0,0 @@
"""SealAI 认证业务逻辑层。
职责
----
1. SSO 换 Bearer token(快报 accesstoken → SealAI Bearer JWT)
2. Token 持久缓存(磁盘文件,CLI/Server 共用)
3. Client 对象内存缓存(模块级 dict,Server 连接池复用;CLI 进程结束自动回收)
4. 401 自动恢复:清除内存 client + 磁盘 token → 重取 → 单次重试
5. 对上层(commands/server)隐藏 SealAiClient 的创建与关闭
对外接口
--------
- get_whoami(corp_id, force_refresh) — 查询用户身份
- invalidate_token(corp_id) — 强制清除缓存(外部显式调用场景)
内部函数(服务层内部使用,不对外导出)
--------------------------------------
- _resolve_corp_id(corp_id) — 解析 corp_id,None 时用当前企业
- _get_or_create_client(corp_id, force) — 带缓存的 client 工厂
- _sealai_call(corp_id, fn, *args, **kwargs) — 调用 SealAI API,401 时自动恢复并重试
缓存设计
--------
磁盘(~/.config/ekb-cli/sealai_tokens.json):
{ "corpId": { "token": "...", "fetched_at": 1712345678 } }
→ CLI 进程间共享,TTL = _TOKEN_TTL 秒
内存(模块级 _client_cache):
{ "corpId": (SealAiClient, fetched_at_float) }
→ 进程内复用 httpx 连接池;CLI 进程结束自然回收,Server 长期保持
两层缓存的 TTL 相同(_TOKEN_TTL)。token 刷新时同步驱逐内存 client,确保
client 携带的 Authorization header 始终与最新 token 一致。
"""
from __future__ import annotations
import json
import time
from pathlib import Path
from typing import Any, Callable
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"
_TOKEN_TTL = 3600 # 保守 1 小时,到期前强制刷新
# ── 内存 client 缓存 ──────────────────────────────────────────────────────────
# key: corp_id, value: (SealAiClient, fetched_at)
# CLI 进程结束自动回收;Server 进程中长期保持,复用 httpx 连接池。
_client_cache: dict[str, tuple[SealAiClient, float]] = {}
# ── 磁盘 token 缓存(私有) ───────────────────────────────────────────────────
def _load_token_cache() -> dict:
if _TOKEN_CACHE_PATH.exists():
try:
return json.loads(_TOKEN_CACHE_PATH.read_text())
except (json.JSONDecodeError, OSError):
pass
return {}
def _save_token_cache(cache: dict) -> None:
_TOKEN_CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
_TOKEN_CACHE_PATH.write_text(json.dumps(cache, indent=2, ensure_ascii=False))
def _fetch_token(corp_id: str, access_token: str) -> str:
"""用快报 accesstoken 向 SealAI 换取 Bearer JWT(SSO)。"""
url = f"https://{corp_id.lower()}.sealai.cc/api/auth/oauth2/session/oem-hosecloud"
try:
resp = httpx.get(
url,
params={"token": access_token, "returnToken": "1"},
headers={"Accept": "application/json"},
timeout=15,
follow_redirects=True,
)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
raise AuthenticationError("快报 token 无效,无法登录 SealAI")
raise ApiResponseError(e.response.status_code, str(e))
data = resp.json()
# 响应:{ "token": "..." } 或 { "data": { "token": "..." } }
token = data.get("token") or (data.get("data") or {}).get("token")
if not token:
raise AuthenticationError(f"SealAI SSO 响应中未找到 token:{data}")
return token
def _get_bearer_token(corp_id: str, force_refresh: bool = False) -> str:
"""获取 Bearer token(优先读磁盘缓存,过期或 force_refresh 时重新换取)。
此函数为内部实现细节,外部不应直接调用。
"""
cache = _load_token_cache()
entry = cache.get(corp_id, {})
now = int(time.time())
if not force_refresh and entry.get("token") and (now - entry.get("fetched_at", 0)) < _TOKEN_TTL:
return entry["token"]
corp = ekb_config.get_corp(corp_id)
if not corp:
raise NotLoggedInError(f"企业 {corp_id} 未配置快报认证,请先运行 ekb auth add")
token = _fetch_token(corp_id, corp["access_token"])
cache[corp_id] = {"token": token, "fetched_at": now}
_save_token_cache(cache)
return token
# ── 对外公共接口 ──────────────────────────────────────────────────────────────
def invalidate_token(corp_id: str) -> None:
"""清除指定企业的全部缓存(磁盘 token + 内存 client)。
调用场景:
- 用户显式执行 --refresh 参数
- 服务层内部在 401 后自动调用(见 _sealai_call)
清除内存 client 是必要的:client 构造时已将 token 写入 Authorization header,
token 失效后若继续复用 client,所有请求都会继续 401。
"""
# 清磁盘
cache = _load_token_cache()
cache.pop(corp_id, None)
_save_token_cache(cache)
# 清内存:同时 close 旧 client,释放 httpx 连接池(Server 长进程尤为重要)
old = _client_cache.pop(corp_id, None)
if old is not None:
old[0].close()
def get_bearer_token(corp_id: str, force_refresh: bool = False) -> str:
"""获取当前企业的 Bearer JWT 字符串(主要供调试 / 外部集成使用)。
正常业务调用应走 _sealai_call,不需要直接拿 token。
"""
if corp_id is None:
corp_id = ekb_config.get_current_corp_id()
if not corp_id:
raise NotLoggedInError()
return _get_bearer_token(corp_id, force_refresh=force_refresh)
# ── 内部工具函数 ──────────────────────────────────────────────────────────────
def _resolve_corp_id(corp_id: str | None) -> str:
"""将 None 解析为当前配置企业的 corp_id,未登录时抛 NotLoggedInError。"""
if corp_id is not None:
return corp_id
resolved = ekb_config.get_current_corp_id()
if not resolved:
raise NotLoggedInError()
return resolved
def _get_or_create_client(corp_id: str, force_refresh: bool = False) -> SealAiClient:
"""带 TTL 缓存的 SealAiClient 工厂。
缓存命中条件:
- 内存中有该 corp_id 的 client
- 距创建时间未超过 _TOKEN_TTL
- 未强制刷新
缓存未命中时:重新获取 token(走磁盘缓存或 SSO),创建新 client,写入内存缓存。
"""
now = time.time()
if not force_refresh:
cached = _client_cache.get(corp_id)
if cached:
client, fetched_at = cached
if now - fetched_at < _TOKEN_TTL:
return client
# 缓存未命中或强制刷新:获取 token,构造新 client
# 若缓存里已有旧 client(TTL 到期),先 close 释放连接池,再替换
token = _get_bearer_token(corp_id, force_refresh=force_refresh)
client = SealAiClient(corp_id=corp_id, bearer_token=token)
old = _client_cache.get(corp_id)
if old is not None:
old[0].close()
_client_cache[corp_id] = (client, now)
return client
def _sealai_call(corp_id: str, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""统一的 SealAI API 调用入口,内置 401 自动恢复与单次重试。
调用流程:
1. 从缓存获取(或新建)SealAiClient
2. 调用 fn(client, *args, **kwargs)
3. 若抛 AuthenticationError(401):
a. 清除内存 client + 磁盘 token(invalidate_token)
b. 强制重新获取 token,构造新 client
c. 重试一次 fn(new_client, *args, **kwargs)
d. 若仍然 401 则向上抛出
所有 SealAI 业务函数都应通过此函数发起调用,不应自行管理 client。
"""
client = _get_or_create_client(corp_id)
try:
return fn(client, *args, **kwargs)
except AuthenticationError:
# token 已被服务端吊销或提前失效,清缓存重试一次
invalidate_token(corp_id)
client = _get_or_create_client(corp_id, force_refresh=True)
return fn(client, *args, **kwargs)
def get_whoami(corp_id: str | None = None, force_refresh: bool = False) -> MeData:
"""查询当前 SealAI 用户身份及租户信息。
commands/server 调用此函数,无需感知 SealAiClient 的存在。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
force_refresh: 强制刷新 Bearer token(token 被手动吊销后使用)
"""
resolved = _resolve_corp_id(corp_id)
if force_refresh:
invalidate_token(resolved)
return _sealai_call(resolved, api_get_me)
@@ -1,39 +0,0 @@
"""SealAI 计费 / 订阅业务逻辑层。
不接受 SealAiClient 参数,由 auth_service._sealai_call 统一管理 client 生命周期。
调用方只需传 corp_id(None 表示使用当前企业)。
功能配额 code 参考
------------------
ai-approval AI 审批余额(balance 型)
approval-rules 审核规则配额(quota 型)
ai-fill AI 填单开关(enabled 型)
financial-policies 财务制度配额(quota 型)
knowledge-documents 知识文档配额(quota 型)
"""
from ekb_cli.api.sealai import get_billing_status
from ekb_cli.api.sealai.schemas import BillingStatusData, Feature
from ekb_cli.services.sealai.auth_service import _resolve_corp_id, _sealai_call
def query_billing_status(corp_id: str | None = None) -> BillingStatusData:
"""查询当前企业订阅状态及各功能配额。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
"""
resolved = _resolve_corp_id(corp_id)
return _sealai_call(resolved, get_billing_status)
def get_feature_usage(corp_id: str | None = None, code: str = "") -> Feature | None:
"""查询单个功能项使用情况,不存在时返回 None。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
code: 功能 code,见模块 docstring
"""
resolved = _resolve_corp_id(corp_id)
status = _sealai_call(resolved, get_billing_status)
return status.get_feature(code)
@@ -1,180 +0,0 @@
"""SealAI 知识文档业务逻辑层。
管理知识文档的增删改查。
知识文档是 AI 审批的训练素材,支持按场景(audit/fill)分类,
内容以 Markdown 格式存储,前端可渲染。
不接受 SealAiClient 参数,由 auth_service._sealai_call 统一管理 client 生命周期。
调用方只需传 corp_id(None 表示使用当前企业)。
枚举常量
--------
scenarios(适用场景):
"audit" —— AI 审批场景(审单、规则匹配)
"fill" —— AI 填单场景(智能填报)
status(文档状态):
"published" —— 已发布,AI 可读取
"draft" —— 草稿,AI 不读取
content_type(内容类型):
"policy" —— 公司政策(默认)
其他值视 SealAI 平台支持情况而定
tags:
"__all__" —— 适用于全部分类(特殊保留值)
"""
from typing import Optional
from ekb_cli.api.sealai.knowledge_api import (
list_articles,
get_article,
create_article,
patch_article,
)
from ekb_cli.api.sealai.schemas import (
KnowledgeArticle,
KnowledgeArticleListData,
)
from ekb_cli.services.sealai.auth_service import _resolve_corp_id, _sealai_call
# 合法场景值
_VALID_SCENARIOS = {"audit", "fill"}
# 合法状态值
_VALID_STATUSES = {"published", "draft"}
def get_articles(
corp_id: str | None = None,
*,
scenarios: Optional[list[str]] = None,
offset: int = 0,
limit: int = 20,
sort_by: str = "createdAt",
sort_order: str = "desc",
) -> KnowledgeArticleListData:
"""查询知识文档列表。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
scenarios: 按场景过滤,可选值 \"audit\" | \"fill\",None 表示不过滤
offset: 分页偏移量(默认 0)
limit: 每页数量(默认 20,建议不超过 100)
sort_by: 排序字段(默认 createdAt)
sort_order: \"asc\" | \"desc\"(默认 desc,最新在前)
"""
if scenarios:
_validate_scenarios(scenarios)
resolved = _resolve_corp_id(corp_id)
return _sealai_call(
resolved, list_articles,
scenarios=scenarios,
offset=offset,
limit=limit,
sort_by=sort_by,
sort_order=sort_order,
)
def get_article_detail(corp_id: str | None = None, article_id: str = "") -> KnowledgeArticle:
"""查询单篇知识文档详情。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
article_id: 文档 ID
"""
resolved = _resolve_corp_id(corp_id)
return _sealai_call(resolved, get_article, article_id)
def add_article(
corp_id: str | None = None,
*,
title: str,
purpose: str,
content: str,
content_type: str = "policy",
status: str = "published",
scenarios: Optional[list[str]] = None,
tags: Optional[list[str]] = None,
) -> KnowledgeArticle:
"""新建知识文档。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
title: 文档标题
purpose: 适用说明
content: 正文(Markdown 格式)
content_type: 内容类型,默认 \"policy\"
status: \"published\" | \"draft\",默认 \"published\"
scenarios: 适用场景,如 [\"audit\", \"fill\"]
tags: 标签列表,\"__all__\" 表示全部适用
"""
if status not in _VALID_STATUSES:
from ekb_cli.errors import EkbError
raise EkbError(f"status 无效:{status!r},合法值为 {sorted(_VALID_STATUSES)}", code=422)
if scenarios:
_validate_scenarios(scenarios)
resolved = _resolve_corp_id(corp_id)
return _sealai_call(
resolved, create_article,
title=title,
purpose=purpose,
content=content,
content_type=content_type,
status=status,
scenarios=scenarios,
tags=tags,
)
def edit_article(
corp_id: str | None = None,
article_id: str = "",
*,
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,
) -> KnowledgeArticle:
"""更新知识文档(只传需要改动的字段)。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
article_id: 文档 ID
其余参数: 对应字段的新值,不传则保持原值
"""
if status is not None and status not in _VALID_STATUSES:
from ekb_cli.errors import EkbError
raise EkbError(f"status 无效:{status!r},合法值为 {sorted(_VALID_STATUSES)}", code=422)
if scenarios is not None:
_validate_scenarios(scenarios)
resolved = _resolve_corp_id(corp_id)
return _sealai_call(
resolved, patch_article,
article_id,
title=title,
purpose=purpose,
content=content,
content_type=content_type,
status=status,
enabled=enabled,
scenarios=scenarios,
tags=tags,
)
# ── 内部校验 ──────────────────────────────────────────────────────────────────
def _validate_scenarios(scenarios: list[str]) -> None:
invalid = set(scenarios) - _VALID_SCENARIOS
if invalid:
from ekb_cli.errors import EkbError
raise EkbError(
f"scenarios 包含无效值:{sorted(invalid)},合法值为 {sorted(_VALID_SCENARIOS)}",
code=422,
)
@@ -1,81 +0,0 @@
"""SealAI 风格偏好业务逻辑层。
管理 AI 审批配置的读取与更新(决策场景提示词 + 集成系统信息)。
不接受 SealAiClient 参数,由 auth_service._sealai_call 统一管理 client 生命周期。
调用方只需传 corp_id(None 表示使用当前企业)。
核心设计:POST 是整体替换语义,因此 update_decision_preferences() 会先 GET
当前配置,patch 指定字段,再整体 POST 回去——对上层调用方透明。
"""
from ekb_cli.api.sealai.preference_api import (
get_ai_approval_config,
save_ai_approval_config,
)
from ekb_cli.api.sealai.schemas import (
AiApprovalConfig,
AiApprovalSaveResult,
DecisionPreferences,
)
from ekb_cli.services.sealai.auth_service import _resolve_corp_id, _sealai_call
def get_preference(corp_id: str | None = None) -> AiApprovalConfig:
"""查询当前 AI 审批配置(风格偏好 + 集成系统信息)。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
"""
resolved = _resolve_corp_id(corp_id)
return _sealai_call(resolved, get_ai_approval_config)
def update_decision_preferences(
corp_id: str | None = None,
*,
explicit_approve: str | None = None,
explicit_reject: str | None = None,
exempt_approve: str | None = None,
review: str | None = None,
) -> AiApprovalSaveResult:
"""Patch 式更新决策偏好(只传需要改动的字段)。
内部会先 GET 当前配置,合并改动后整体 POST 回去,
确保 integrations 等无关字段不丢失。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
explicit_approve: 明确通过的条件描述(不传则保持不变)
explicit_reject: 明确拒绝的条件描述(不传则保持不变)
exempt_approve: 豁免通过的条件描述(不传则保持不变)
review: 转人工判断的条件描述(不传则保持不变)
Returns:
AiApprovalSaveResult,含 success 标志。
"""
resolved = _resolve_corp_id(corp_id)
current = _sealai_call(resolved, get_ai_approval_config)
prefs = current.decisionPreferences
new_prefs = DecisionPreferences(
explicitApprove=explicit_approve if explicit_approve is not None else prefs.explicitApprove,
explicitReject=explicit_reject if explicit_reject is not None else prefs.explicitReject,
exemptApprove=exempt_approve if exempt_approve is not None else prefs.exemptApprove,
review=review if review is not None else prefs.review,
)
updated = current.model_copy(update={"decisionPreferences": new_prefs})
return _sealai_call(resolved, save_ai_approval_config, updated)
def save_preference(
corp_id: str | None = None,
config: AiApprovalConfig | None = None,
) -> AiApprovalSaveResult:
"""直接保存完整的 AI 审批配置(整体替换,适合高阶调用方)。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
config: 完整配置对象
"""
resolved = _resolve_corp_id(corp_id)
return _sealai_call(resolved, save_ai_approval_config, config)
@@ -1,144 +0,0 @@
"""SealAI 审核规则业务逻辑层。
管理草稿区规则的增删改查,以及已发布版本历史的查询和发布操作。
不接受 SealAiClient 参数,由 auth_service._sealai_call 统一管理 client 生命周期。
调用方只需传 corp_id(None 表示使用当前企业)。
strictness 取值
---------------
MUST_FOLLOW 必须遵守(最严格,违规直接驳回)
SHOULD_FOLLOW 应该遵守(违规可提示但不强制驳回)
SUGGESTION 建议遵守(仅作为参考提示)
"""
from ekb_cli.api.sealai.rules_api import (
list_rules,
create_rule,
update_rule,
delete_rule,
list_rule_set_versions,
publish_rule_set_version,
)
from ekb_cli.api.sealai.schemas import (
DraftRule,
DraftRulesData,
RuleSetVersion,
PublishVersionData,
)
from ekb_cli.services.sealai.auth_service import _resolve_corp_id, _sealai_call
# ── 草稿区规则 CRUD ────────────────────────────────────────────────────────────
def get_draft_rules(corp_id: str | None = None) -> DraftRulesData:
"""查询草稿区所有审核规则。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
"""
resolved = _resolve_corp_id(corp_id)
return _sealai_call(resolved, list_rules)
def add_draft_rule(
corp_id: str | None = None,
*,
description: str,
scope: str,
strictness: str = "MUST_FOLLOW",
) -> DraftRule:
"""新建草稿审核规则。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
description: 规则描述
scope: 适用场景(费用类型等自由文本)
strictness: MUST_FOLLOW | SHOULD_FOLLOW | SUGGESTION,默认 MUST_FOLLOW
"""
_validate_strictness(strictness)
resolved = _resolve_corp_id(corp_id)
return _sealai_call(
resolved, create_rule,
description=description, scope=scope, strictness=strictness,
)
def edit_draft_rule(
corp_id: str | None = None,
rule_id: str = "",
*,
description: str | None = None,
scope: str | None = None,
strictness: str | None = None,
) -> DraftRule:
"""更新草稿规则(只传要改动的字段)。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
rule_id: 规则 ID
description: 新描述(不传则保持原值)
scope: 新适用场景(不传则保持原值)
strictness: 新严格度(不传则保持原值)
"""
if strictness is not None:
_validate_strictness(strictness)
resolved = _resolve_corp_id(corp_id)
return _sealai_call(
resolved, update_rule,
rule_id, description=description, scope=scope, strictness=strictness,
)
def remove_draft_rule(corp_id: str | None = None, rule_id: str = "") -> None:
"""删除草稿规则。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
rule_id: 规则 ID
"""
resolved = _resolve_corp_id(corp_id)
_sealai_call(resolved, delete_rule, rule_id)
# ── 已发布版本 ────────────────────────────────────────────────────────────────
def get_published_versions(corp_id: str | None = None) -> list[RuleSetVersion]:
"""查询已发布的规则集版本历史(最新版本在前)。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
"""
resolved = _resolve_corp_id(corp_id)
return _sealai_call(resolved, list_rule_set_versions)
def publish_draft_rules(
corp_id: str | None = None,
*,
version_name: str,
) -> PublishVersionData:
"""将当前草稿区规则发布为新版本。
Args:
corp_id: 企业 ID,None 时使用当前配置企业
version_name: 版本名称,建议格式:\"审核规则 版本N\"
Returns:
PublishVersionData,含新版本快照和规则数量
"""
resolved = _resolve_corp_id(corp_id)
return _sealai_call(resolved, publish_rule_set_version, version_name=version_name)
# ── 内部校验 ──────────────────────────────────────────────────────────────────
_VALID_STRICTNESS = {"MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"}
def _validate_strictness(value: str) -> None:
if value not in _VALID_STRICTNESS:
from ekb_cli.errors import EkbError
raise EkbError(
f"strictness 无效:{value!r},合法值为 {sorted(_VALID_STRICTNESS)}",
code=422,
)