From ef076898ea9e680e6db0967d1e070f1d76fc7007 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 14 Apr 2026 18:15:58 +0800 Subject: [PATCH] =?UTF-8?q?SealAI=20=E5=AE=A1=E6=A0=B8=E8=A7=84=E5=88=99?= =?UTF-8?q?=20CLI=20+=20HTTP=20=E8=B7=AF=E7=94=B1=E5=85=A8=E9=83=A8?= =?UTF-8?q?=E5=AE=8C=E6=88=90=EF=BC=8C=E8=A1=A5=E5=85=85=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/modules/sealai.md | 179 +++++++++++++++++++++ src/ekb_cli/commands/sealai/__init__.py | 19 ++- src/ekb_cli/commands/sealai/rule_create.py | 35 ++++ src/ekb_cli/commands/sealai/rule_delete.py | 27 ++++ src/ekb_cli/commands/sealai/rule_update.py | 35 ++++ src/ekb_cli/commands/sealai/rules.py | 46 ++++++ src/ekb_cli/commands/sealai/versions.py | 66 ++++++++ src/ekb_cli/server/sealai_router.py | 112 +++++++++++-- 8 files changed, 504 insertions(+), 15 deletions(-) create mode 100644 docs/modules/sealai.md create mode 100644 src/ekb_cli/commands/sealai/rule_create.py create mode 100644 src/ekb_cli/commands/sealai/rule_delete.py create mode 100644 src/ekb_cli/commands/sealai/rule_update.py create mode 100644 src/ekb_cli/commands/sealai/rules.py create mode 100644 src/ekb_cli/commands/sealai/versions.py diff --git a/docs/modules/sealai.md b/docs/modules/sealai.md new file mode 100644 index 0000000..fc4c9fb --- /dev/null +++ b/docs/modules/sealai.md @@ -0,0 +1,179 @@ +# SealAI 模块 + +## 概述 + +SealAI(`{corpId.lower()}.sealai.cc`)是独立于快报主站的 AI 填单/审批平台, +采用 Next.js App Router + Kubernetes/Istio 后端,认证体系与快报 HAB 完全独立。 + +本模块按项目三层架构集成进 ekb-cli: + +``` +commands/sealai/ ← CLI 表现层(薄壳) +server/ ← HTTP Server 路由(/sealai/*) +services/sealai/ ← 业务逻辑层 +api/sealai/ ← 传输层(SealAiClient + API 函数) +``` + +--- + +## 认证机制 + +SealAI 使用独立的 Bearer JWT,通过快报 accesstoken SSO 换取: + +``` +快报 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) +``` + +**关键细节:** +- corpId 全小写作为子域名:`ID01Jdq2yIDnMr` → `id01jdq2yidnmr.sealai.cc` +- token 自动缓存,TTL 1 小时,到期自动重新换取 +- 遇到 401 调用 `invalidate_token(corp_id)` 清除缓存后重试 + +--- + +## 已实现 API + +### 认证 + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/v1/auth/me` | 当前用户身份(user + tenant) | + +### 计费 + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/v1/billing/status` | 订阅状态 + 各功能配额 | + +### 审核规则(草稿区) + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/v1/rules` | 草稿规则列表(含 hasPendingDeletes) | +| POST | `/api/v1/rules` | 新建草稿规则 | +| PUT | `/api/v1/rules/{id}` | 更新草稿规则(partial,只传改动字段) | +| DELETE | `/api/v1/rules/{id}` | 删除草稿规则 | + +### 审核规则(已发布版本历史) + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/v1/rule-set-versions` | 已发布版本列表(倒序,含每版规则快照) | + +--- + +## 数据模型 + +### DraftRule(草稿规则) + +```python +id: str +description: str # 规则描述 +scope: str # 适用场景(自由文本) +strictness: str # MUST_FOLLOW | SHOULD_FOLLOW | SUGGESTION +status: str # 固定为 "DRAFT" +createdAt: int # 毫秒时间戳 +updatedAt: int +``` + +### RuleSetVersion(已发布版本) + +```python +id: str +versionNumber: int +versionName: str # 如 "审核规则 版本4" +publishedByName: str +publishedAt: int # 毫秒时间戳 +rules: list[PublishedRuleSnapshot] # 快照,无 id,不可变 +``` + +### strictness 枚举 + +| 值 | 含义 | +|----|------| +| `MUST_FOLLOW` | 必须遵守 | +| `SHOULD_FOLLOW` | 应当遵守 | +| `SUGGESTION` | 建议 | + +### Feature(功能配额)三种形态 + +| 形态 | 字段 | 示例 code | +|------|------|-----------| +| 余额型 | `balance / totalQuota / totalUsed` | `ai-approval` | +| 配额型 | `quota / used / remaining` | `approval-rules` | +| 开关型 | `enabled` | `ai-fill`, `webhook` | + +--- + +## CLI 命令 + +```bash +# 认证 / 计费 +ekb sealai whoami # 当前用户 + 租户信息 +ekb sealai whoami --refresh # 强制刷新 Bearer token +ekb sealai billing # 订阅状态 + 功能配额表 + +# 草稿规则 +ekb sealai rules # 列出草稿规则 +ekb sealai rule-create # 交互式新建(或用 --description/--scope/--strictness) +ekb sealai rule-update # 更新(--description/--scope/--strictness,只传要改的) +ekb sealai rule-delete # 删除(有二次确认,-y 跳过) + +# 版本历史 +ekb sealai versions # 版本列表(版本号/发布者/规则数/时间) +ekb sealai versions --detail # 展开每版规则内容 + +# 通用选项 +--corp # 指定企业(不切换当前企业) +``` + +--- + +## HTTP 接口(`/sealai/*`) + +| CLI 命令 | HTTP 端点 | 方法 | +|---|---|---| +| `ekb sealai whoami` | `GET /sealai/me` | GET | +| `ekb sealai billing` | `GET /sealai/billing` | GET | +| `ekb sealai rules` | `GET /sealai/rules` | GET | +| `ekb sealai rule-create` | `POST /sealai/rules` | POST | +| `ekb sealai rule-update ` | `PUT /sealai/rules/{rule_id}` | PUT | +| `ekb sealai rule-delete ` | `DELETE /sealai/rules/{rule_id}` | DELETE | +| `ekb sealai versions` | `GET /sealai/rule-set-versions` | GET | + +启动 Server 后访问完整文档:`http://127.0.0.1:9528/docs` + +--- + +## 代码结构 + +``` +src/ekb_cli/ +├── api/sealai/ +│ ├── client.py SealAiClient(httpx,Bearer JWT) +│ ├── schemas.py Pydantic 数据模型 +│ ├── auth_api.py get_me() +│ ├── billing_api.py get_billing_status() +│ └── rules_api.py list_rules / create_rule / update_rule / delete_rule / list_rule_set_versions +│ +├── services/sealai/ +│ ├── auth_service.py SSO token 换取 + 缓存(~/.config/ekb-cli/sealai_tokens.json) +│ ├── billing_service.py query_billing_status / get_feature_usage +│ └── rules_service.py get_draft_rules / add_draft_rule / edit_draft_rule / remove_draft_rule / get_published_versions +│ +├── 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 +│ +└── server/sealai_router.py 所有 /sealai/* 路由 +``` diff --git a/src/ekb_cli/commands/sealai/__init__.py b/src/ekb_cli/commands/sealai/__init__.py index 95964f3..e4dbce2 100644 --- a/src/ekb_cli/commands/sealai/__init__.py +++ b/src/ekb_cli/commands/sealai/__init__.py @@ -1,15 +1,30 @@ """sealai 子命令组 对应 CLI 命令: - ekb sealai whoami → 查看当前 SealAI 用户身份及租户信息 - ekb sealai billing → 查看当前企业 SealAI 订阅状态及功能配额 + 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 → 查看已发布规则集版本历史 """ 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 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) diff --git a/src/ekb_cli/commands/sealai/rule_create.py b/src/ekb_cli/commands/sealai/rule_create.py new file mode 100644 index 0000000..c7f3ced --- /dev/null +++ b/src/ekb_cli/commands/sealai/rule_create.py @@ -0,0 +1,35 @@ +"""sealai rule-create:新建草稿审核规则 + +表现层:交互式输入 + rich 输出。 +业务逻辑委托给 services.sealai.rules_service。 +""" + +import typer +from rich import print as rprint + +from ekb_cli.services.sealai import get_sealai_client, 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) + + client = get_sealai_client(corp_id=corp_id) + rule = add_draft_rule(client, description=description, scope=scope, strictness=strictness) + rprint(f"[green]✓[/green] 规则已创建:[bold]{rule.description}[/bold](ID: {rule.id})") diff --git a/src/ekb_cli/commands/sealai/rule_delete.py b/src/ekb_cli/commands/sealai/rule_delete.py new file mode 100644 index 0000000..3d21603 --- /dev/null +++ b/src/ekb_cli/commands/sealai/rule_delete.py @@ -0,0 +1,27 @@ +"""sealai rule-delete:删除草稿审核规则 + +表现层:二次确认 + rich 输出。 +业务逻辑委托给 services.sealai.rules_service。 +""" + +import typer +from rich import print as rprint + +from ekb_cli.services.sealai import get_sealai_client, 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() + + client = get_sealai_client(corp_id=corp_id) + remove_draft_rule(client, rule_id) + rprint(f"[green]✓[/green] 规则 {rule_id} 已删除") diff --git a/src/ekb_cli/commands/sealai/rule_update.py b/src/ekb_cli/commands/sealai/rule_update.py new file mode 100644 index 0000000..8c1c4a5 --- /dev/null +++ b/src/ekb_cli/commands/sealai/rule_update.py @@ -0,0 +1,35 @@ +"""sealai rule-update:更新草稿审核规则 + +表现层:只负责参数解析 + rich 输出。 +业务逻辑委托给 services.sealai.rules_service。 +""" + +import typer +from rich import print as rprint + +from ekb_cli.services.sealai import get_sealai_client, 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() + + client = get_sealai_client(corp_id=corp_id) + rule = edit_draft_rule( + client, rule_id, + description=description, + scope=scope, + strictness=strictness, + ) + rprint(f"[green]✓[/green] 规则已更新:[bold]{rule.description}[/bold](ID: {rule.id})") diff --git a/src/ekb_cli/commands/sealai/rules.py b/src/ekb_cli/commands/sealai/rules.py new file mode 100644 index 0000000..74ee18e --- /dev/null +++ b/src/ekb_cli/commands/sealai/rules.py @@ -0,0 +1,46 @@ +"""sealai rules:查看草稿规则列表 + +表现层:只负责 rich 格式化输出。 +业务逻辑委托给 services.sealai.rules_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_sealai_client, 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,默认使用当前企业"), +): + """查看草稿区所有审核规则""" + client = get_sealai_client(corp_id=corp_id) + data = get_draft_rules(client) + + 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]") diff --git a/src/ekb_cli/commands/sealai/versions.py b/src/ekb_cli/commands/sealai/versions.py new file mode 100644 index 0000000..3848c32 --- /dev/null +++ b/src/ekb_cli/commands/sealai/versions.py @@ -0,0 +1,66 @@ +"""sealai versions:查看已发布规则集版本历史 + +表现层:只负责 rich 格式化输出。 +业务逻辑委托给 services.sealai.rules_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_sealai_client, 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="展开每个版本的规则列表"), +): + """查看已发布规则集版本历史""" + client = get_sealai_client(corp_id=corp_id) + versions = get_published_versions(client) + + 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) diff --git a/src/ekb_cli/server/sealai_router.py b/src/ekb_cli/server/sealai_router.py index 21e39fe..b14ff66 100644 --- a/src/ekb_cli/server/sealai_router.py +++ b/src/ekb_cli/server/sealai_router.py @@ -1,30 +1,45 @@ """Server:SealAI 路由 对应 CLI 命令: - ekb sealai whoami → GET /sealai/me - ekb sealai billing → GET /sealai/billing + 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 注意:SealAI 接口使用独立的 SealAiClient(Bearer JWT), 不使用快报主站的 EkbClient(三 Header 认证)。 """ from fastapi import APIRouter, Query +from pydantic import BaseModel from ekb_cli.services.sealai import ( get_sealai_client, query_billing_status, + get_draft_rules, + add_draft_rule, + edit_draft_rule, + remove_draft_rule, + get_published_versions, ) from ekb_cli.api.sealai import get_me -from ekb_cli.api.sealai.schemas import MeData, BillingStatusData +from ekb_cli.api.sealai.schemas import ( + MeData, + BillingStatusData, + DraftRule, + DraftRulesData, + RuleSetVersion, +) router = APIRouter() -@router.get( - "/me", - response_model=MeData, - summary="查看当前 SealAI 用户身份及租户信息", -) +# ── 认证 / 计费 ──────────────────────────────────────────────────────────────── + +@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"), @@ -33,13 +48,84 @@ def sealai_whoami( return get_me(client) -@router.get( - "/billing", - response_model=BillingStatusData, - summary="查看 SealAI 订阅状态及功能配额", -) +@router.get("/billing", response_model=BillingStatusData, summary="查看 SealAI 订阅状态及功能配额") def sealai_billing( corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"), ): client = get_sealai_client(corp_id=corp_id) return query_billing_status(client) + + +# ── 审核规则(草稿区) ───────────────────────────────────────────────────────── + +@router.get("/rules", response_model=DraftRulesData, summary="查看草稿区审核规则列表") +def sealai_list_rules( + corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"), +): + client = get_sealai_client(corp_id=corp_id) + return get_draft_rules(client) + + +class RuleCreateRequest(BaseModel): + description: str + scope: str + strictness: str = "MUST_FOLLOW" + + +@router.post("/rules", response_model=DraftRule, summary="新建草稿审核规则") +def sealai_create_rule( + body: RuleCreateRequest, + corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"), +): + client = get_sealai_client(corp_id=corp_id) + return add_draft_rule( + client, + description=body.description, + scope=body.scope, + strictness=body.strictness, + ) + + +class RuleUpdateRequest(BaseModel): + description: str | None = None + scope: str | None = None + strictness: str | None = None + + +@router.put("/rules/{rule_id}", response_model=DraftRule, summary="更新草稿审核规则(partial)") +def sealai_update_rule( + rule_id: str, + body: RuleUpdateRequest, + corp_id: str = Query(None, description="企业 corpId,不传则使用当前企业"), +): + client = get_sealai_client(corp_id=corp_id) + return edit_draft_rule( + client, 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,不传则使用当前企业"), +): + client = get_sealai_client(corp_id=corp_id) + remove_draft_rule(client, 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,不传则使用当前企业"), +): + client = get_sealai_client(corp_id=corp_id) + return get_published_versions(client)