重构第3批:CLI 瘦化 + 新增 FastAPI Server
CLI 瘦化(commands/ 全部 10 个命令文件): - 移除内联的参数校验和编排逻辑,改为调用对应 service 函数 - 统一错误处理:捕获 EkbError,rich 红字输出并 Exit(1) - auth.py:调用 auth_service,不再直接操作 config 模块 新增 server/ 目录(FastAPI HTTP Server): - __init__.py:create_app() 工厂,注册三个路由组,统一 EkbError 异常处理 - deps.py:ClientDep 类型别名,FastAPI 依赖注入 EkbClient - auth_router.py:/auth/* 5 个端点,对应 ekb auth 命令组 - agent_router.py:/agents/* 7 个端点,含高阶 /dedup-rules 接口 - rule_router.py:/rules/* 4 个端点,对应 ekb agent rule-* 命令
This commit is contained in:
1 parent
475ce518f9
commit
db378b9140
15 files changed
+467
-215
No files matched your search
@@ -1,48 +1,27 @@
|
||||
"""ekb agent copy <id>:复制智能审核 Agent"""
|
||||
"""ekb agent copy <id>:复制智能审核 Agent(表现层)"""
|
||||
|
||||
import typer
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli.api import get_client, get_agent, check_agent_name, save_agent
|
||||
|
||||
MODE_DISPLAY = {0: "全自动", 1: "半自动", 2: "辅助"}
|
||||
from ekb_cli.api import get_client
|
||||
from ekb_cli.services import copy_agent, MODE_DISPLAY
|
||||
|
||||
|
||||
def cmd_copy(
|
||||
agent_id: str = typer.Argument(..., help="要复制的 Agent ID"),
|
||||
):
|
||||
"""复制 Agent(新 Agent 名称为原名称加「(副本)」)"""
|
||||
with get_client() as client:
|
||||
src = get_agent(client, agent_id)
|
||||
if not src:
|
||||
rprint("[red]未找到该 Agent[/red]")
|
||||
raise typer.Exit(1)
|
||||
"""复制 Agent(新 Agent 名称为原名称加「(副本)」)"""
|
||||
from ekb_cli.errors import EkbError
|
||||
|
||||
new_name = src.name + "(副本)"
|
||||
try:
|
||||
with get_client() as client:
|
||||
src, new = copy_agent(client, agent_id)
|
||||
except EkbError as e:
|
||||
rprint(f"[red]{e.message}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
if not check_agent_name(client, new_name):
|
||||
rprint(f"[red]名称「{new_name}」已存在,无法复制[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
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
|
||||
|
||||
data = save_agent(client, payload)
|
||||
|
||||
rprint(f"[green]✓ Agent 复制成功[/green]")
|
||||
rprint(f" 原 Agent:[dim]{src.name}[/dim] → 新 Agent:[bold]{data.name}[/bold]")
|
||||
rprint(f" 新 ID:[dim]{data.id}[/dim]")
|
||||
rprint(f" 模式:{MODE_DISPLAY.get(data.mode, str(data.mode))}")
|
||||
rprint(f" 关联规则数:{len(data.agentRule)}")
|
||||
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)}")
|
||||
@@ -1,15 +1,11 @@
|
||||
"""ekb agent create:新建智能审核 Agent"""
|
||||
"""ekb agent create:新建智能审核 Agent(表现层)"""
|
||||
|
||||
from typing import Optional, List
|
||||
import typer
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli.api import get_client, check_agent_name, save_agent
|
||||
|
||||
MODE_NAMES = {"auto": 0, "semi": 1, "assist": 2}
|
||||
MODE_DISPLAY = {0: "全自动", 1: "半自动", 2: "辅助"}
|
||||
|
||||
DEFAULT_ICON = "https://statics.ekuaibao.com/eui/eui-static/male5.png"
|
||||
from ekb_cli.api import get_client
|
||||
from ekb_cli.services import create_agent, AgentCreateInput, MODE_DISPLAY
|
||||
|
||||
|
||||
def cmd_create(
|
||||
@@ -21,33 +17,32 @@ def cmd_create(
|
||||
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(DEFAULT_ICON, "--icon", help="头像 URL"),
|
||||
icon: str = typer.Option("", "--icon", help="头像 URL(留空使用默认)"),
|
||||
):
|
||||
"""新建智能审核 Agent"""
|
||||
if mode not in MODE_NAMES:
|
||||
rprint(f"[red]mode 必须是 auto / semi / assist,当前:{mode}[/red]")
|
||||
from ekb_cli.errors import EkbError
|
||||
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,
|
||||
)
|
||||
|
||||
try:
|
||||
with get_client() as client:
|
||||
data = create_agent(client, inp)
|
||||
except EkbError as e:
|
||||
rprint(f"[red]{e.message}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
with get_client() as client:
|
||||
if not check_agent_name(client, name):
|
||||
rprint(f"[red]名称「{name}」已存在,请换一个[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
payload = {
|
||||
"icon": icon,
|
||||
"name": name,
|
||||
"description": description,
|
||||
"mode": MODE_NAMES[mode],
|
||||
"agreeTerms": agree_terms,
|
||||
"rejectTerms": reject_terms,
|
||||
"exemptTerms": exempt_terms,
|
||||
"reviewTerms": review_terms,
|
||||
"state": 1,
|
||||
"ruleIds": rule_ids or [],
|
||||
}
|
||||
data = save_agent(client, payload)
|
||||
|
||||
rprint(f"[green]✓ Agent 创建成功[/green]")
|
||||
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))}")
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
"""ekb agent delete <id>:删除智能审核 Agent(需二次确认)"""
|
||||
"""ekb agent delete <id>:删除智能审核 Agent(表现层)
|
||||
|
||||
确认逻辑:
|
||||
- 默认:终端可用时用方向键菜单(questionary),否则降级为文字输入
|
||||
- --ai:强制文字输入模式(适合 AI/脚本非交互式环境)
|
||||
- --yes:跳过确认直接删除
|
||||
"""
|
||||
|
||||
import sys
|
||||
import questionary
|
||||
@@ -7,7 +13,8 @@ from rich import print as rprint
|
||||
from rich.panel import Panel
|
||||
from rich.console import Console
|
||||
|
||||
from ekb_cli.api import get_client, get_agent, delete_agent
|
||||
from ekb_cli.api import get_client
|
||||
from ekb_cli.services import delete_agent
|
||||
|
||||
console = Console()
|
||||
|
||||
@@ -18,55 +25,61 @@ _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 确认,适合非交互式环境"),
|
||||
ai: bool = typer.Option(False, "--ai", help="AI/脚本模式:改用文字输入 y/N 确认"),
|
||||
):
|
||||
"""删除 Agent(不可恢复,操作前会展示 Agent 信息并要求确认)"""
|
||||
with get_client() as client:
|
||||
d = get_agent(client, agent_id)
|
||||
if not d:
|
||||
rprint("[red]未找到该 Agent[/red]")
|
||||
raise typer.Exit(1)
|
||||
from ekb_cli.errors import EkbError
|
||||
|
||||
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,
|
||||
))
|
||||
# 先拉详情用于展示(service 层已处理 NotFoundError)
|
||||
try:
|
||||
with get_client() as client:
|
||||
# 需要先展示再确认,所以分两步使用 client
|
||||
from ekb_cli.services import get_agent as svc_get_agent
|
||||
d = svc_get_agent(client, agent_id)
|
||||
|
||||
if not yes:
|
||||
if ai or not sys.stdin.isatty():
|
||||
# AI / 非交互式模式:文字输入
|
||||
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()
|
||||
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 choice != _CONFIRM:
|
||||
rprint("[dim]已取消[/dim]")
|
||||
raise typer.Exit(0)
|
||||
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()
|
||||
|
||||
delete_agent(client, agent_id)
|
||||
if choice != _CONFIRM:
|
||||
rprint("[dim]已取消[/dim]")
|
||||
raise typer.Exit(0)
|
||||
|
||||
# 确认后执行删除
|
||||
delete_agent(client, agent_id)
|
||||
|
||||
except EkbError as e:
|
||||
rprint(f"[red]{e.message}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
rprint(f"[green]✓ Agent「{d.name}」已删除[/green]")
|
||||
@@ -1,4 +1,4 @@
|
||||
"""ekb agent get <id>:查看 Agent 详情"""
|
||||
"""ekb agent get <id>:查看 Agent 详情(表现层)"""
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
@@ -6,7 +6,8 @@ from rich.panel import Panel
|
||||
from rich.table import Table
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli.api import get_client, get_agent
|
||||
from ekb_cli.api import get_client
|
||||
from ekb_cli.services import get_agent
|
||||
|
||||
console = Console()
|
||||
STATE_MAP = {0: "[dim]草稿[/dim]", 1: "[green]已发布[/green]"}
|
||||
@@ -24,10 +25,6 @@ def cmd_detail(
|
||||
with get_client() as client:
|
||||
d = get_agent(client, agent_id)
|
||||
|
||||
if not d:
|
||||
rprint("[red]未找到该 Agent[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
state = STATE_MAP.get(d.state, str(d.state))
|
||||
mode = MODE_MAP.get(d.mode, str(d.mode))
|
||||
if d.mode == 1:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""ekb agent list:列出所有智能审核 Agent"""
|
||||
"""ekb agent list:列出所有智能审核 Agent(表现层)"""
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
@@ -6,7 +6,7 @@ from rich.table import Table
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli.api import get_client
|
||||
from ekb_cli.api.agent import list_agents
|
||||
from ekb_cli.services import list_agents
|
||||
|
||||
console = Console()
|
||||
STATE_MAP = {0: "[dim]草稿[/dim]", 1: "[green]已发布[/green]"}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
"""ekb agent rule-create:新建审核规则"""
|
||||
"""ekb agent rule-create:新建审核规则(表现层)"""
|
||||
|
||||
import typer
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli.api import get_client, save_rule
|
||||
|
||||
VALID_LEVELS = {"严重", "一般"}
|
||||
from ekb_cli.api import get_client
|
||||
from ekb_cli.services import create_rule
|
||||
|
||||
|
||||
def cmd_rule_create(
|
||||
@@ -14,19 +13,20 @@ def cmd_rule_create(
|
||||
level: str = typer.Option("严重", "--level", "-l", help="风险等级:严重 / 一般"),
|
||||
):
|
||||
"""新建审核规则"""
|
||||
if level not in VALID_LEVELS:
|
||||
rprint(f"[red]错误:--level 只接受 严重 / 一般,当前值:{level}[/red]")
|
||||
from ekb_cli.errors import EkbError
|
||||
|
||||
try:
|
||||
with get_client() as client:
|
||||
rule = create_rule(client, purpose=purpose, description=description, level=level)
|
||||
except EkbError as e:
|
||||
rprint(f"[red]{e.message}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
payload = {"purpose": purpose, "description": description, "level": level}
|
||||
|
||||
with get_client() as client:
|
||||
rule = save_rule(client, payload)
|
||||
|
||||
rprint(f"[green]✓ 规则创建成功[/green]")
|
||||
rprint("[green]✓ 规则创建成功[/green]")
|
||||
rprint(f" 编码:[bold]{rule.code}[/bold]")
|
||||
rprint(f" ID:[dim]{rule.id}[/dim]")
|
||||
rprint(f" 适用场景:{rule.purpose}")
|
||||
rprint(f" 描述:{rule.description}")
|
||||
rprint(f" 风险等级:{'[red]' if rule.level == '严重' else '[yellow]'}{rule.level}[/{'red' if rule.level == '严重' else 'yellow'}]")
|
||||
level_tag = "red" if rule.level == "严重" else "yellow"
|
||||
rprint(f" 风险等级:[{level_tag}]{rule.level}[/{level_tag}]")
|
||||
rprint(f" 创建时间:[dim]{rule.createTime}[/dim]")
|
||||
@@ -1,4 +1,4 @@
|
||||
"""ekb agent rule-get:查看单条规则详情(含关联 Agent 列表)"""
|
||||
"""ekb agent rule-get:查看单条规则详情(表现层)"""
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
@@ -6,7 +6,8 @@ from rich.panel import Panel
|
||||
from rich.table import Table
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli.api import get_client, list_rules
|
||||
from ekb_cli.api import get_client
|
||||
from ekb_cli.services import get_rule
|
||||
|
||||
console = Console()
|
||||
|
||||
@@ -15,19 +16,13 @@ def cmd_rule_detail(
|
||||
rule_ref: str = typer.Argument(..., help="规则 ID 或编码(如 2040826... 或 #0001 或 0001)"),
|
||||
):
|
||||
"""查看单条规则详情(含关联 Agent 列表)"""
|
||||
with get_client() as client:
|
||||
page = list_rules(client)
|
||||
from ekb_cli.errors import EkbError
|
||||
|
||||
# 自适应:纯数字且不超过4位 → 补零对齐后按编码匹配;其余按 ID 匹配
|
||||
if rule_ref.lstrip("#").isdigit() and len(rule_ref.lstrip("#")) <= 4:
|
||||
digits = rule_ref.lstrip("#")
|
||||
code = f"#{digits.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:
|
||||
rprint(f"[red]未找到规则:{rule_ref}[/red]")
|
||||
try:
|
||||
with get_client() as client:
|
||||
rule = get_rule(client, rule_ref)
|
||||
except EkbError as e:
|
||||
rprint(f"[red]{e.message}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
level_color = "red" if rule.level == "严重" else "yellow"
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""ekb agent rules:列出企业所有审核规则"""
|
||||
"""ekb agent rules:列出企业所有审核规则(表现层)"""
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli.api import get_client, list_rules
|
||||
from ekb_cli.api import get_client
|
||||
from ekb_cli.services import list_rules
|
||||
|
||||
console = Console()
|
||||
|
||||
@@ -18,18 +19,24 @@ def cmd_rule_list(
|
||||
level: str = typer.Option(None, "--level", "-l", help="按风险等级筛选:严重 / 一般"),
|
||||
):
|
||||
"""列出企业所有审核规则"""
|
||||
with get_client() as client:
|
||||
page = list_rules(client)
|
||||
from ekb_cli.errors import EkbError
|
||||
|
||||
items = page.items
|
||||
if level:
|
||||
items = [r for r in items if r.level == level]
|
||||
try:
|
||||
with get_client() as client:
|
||||
page, items = list_rules(client, level=level)
|
||||
except EkbError as e:
|
||||
rprint(f"[red]{e.message}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
if not items:
|
||||
rprint("[dim](暂无规则)[/dim]")
|
||||
return
|
||||
|
||||
title = f"审核规则(共 {page.totalItems} 条,筛选:{level})" if level else f"审核规则(共 {page.totalItems} 条)"
|
||||
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:
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
"""ekb agent update <id>:修改 Agent 配置"""
|
||||
"""ekb agent update <id>:修改 Agent 配置(表现层)"""
|
||||
|
||||
from typing import Optional
|
||||
import typer
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli.api import get_client, get_agent, save_agent
|
||||
from ekb_cli.api import get_client
|
||||
from ekb_cli.services import update_agent, AgentUpdateInput, MODE_DISPLAY
|
||||
|
||||
MODE_NAMES = {"auto": 0, "semi": 1, "assist": 2}
|
||||
MODE_DISPLAY = {0: "全自动", 1: "半自动", 2: "辅助"}
|
||||
STATE_DISPLAY = {0: "启用", 1: "禁用"}
|
||||
|
||||
|
||||
@@ -24,45 +23,28 @@ def cmd_update(
|
||||
review_terms: Optional[str] = typer.Option(None, "--review-terms", help="转人工条款"),
|
||||
):
|
||||
"""修改 Agent 配置(只传需要修改的字段)"""
|
||||
mode_val = None
|
||||
if mode is not None:
|
||||
if mode not in MODE_NAMES:
|
||||
rprint(f"[red]mode 必须是 auto / semi / assist,当前:{mode}[/red]")
|
||||
raise typer.Exit(1)
|
||||
mode_val = MODE_NAMES[mode]
|
||||
from ekb_cli.errors import EkbError
|
||||
|
||||
if sampling_rate is not None and not (0 <= sampling_rate <= 100):
|
||||
rprint("[red]sampling-rate 范围是 0-100[/red]")
|
||||
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,
|
||||
)
|
||||
|
||||
try:
|
||||
with get_client() as client:
|
||||
saved = update_agent(client, inp)
|
||||
except EkbError as e:
|
||||
rprint(f"[red]{e.message}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
with get_client() as client:
|
||||
d = get_agent(client, agent_id)
|
||||
if not d:
|
||||
rprint("[red]未找到该 Agent[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
payload: dict = {
|
||||
"id": d.id,
|
||||
"icon": d.icon,
|
||||
"name": name if name is not None else d.name,
|
||||
"description": description if description is not None else d.description,
|
||||
"mode": mode_val if mode_val is not None else d.mode,
|
||||
"agreeTerms": agree_terms if agree_terms is not None else d.agreeTerms,
|
||||
"rejectTerms": reject_terms if reject_terms is not None else d.rejectTerms,
|
||||
"exemptTerms": exempt_terms if exempt_terms is not None else d.exemptTerms,
|
||||
"reviewTerms": review_terms if review_terms is not None else d.reviewTerms,
|
||||
"state": state if state is not None else d.state,
|
||||
"ruleIds": [r.id for r in d.agentRule],
|
||||
}
|
||||
|
||||
effective_mode = payload["mode"]
|
||||
if effective_mode == 1:
|
||||
payload["samplingRate"] = (
|
||||
sampling_rate if sampling_rate is not None else d.samplingRate
|
||||
)
|
||||
|
||||
saved = save_agent(client, payload)
|
||||
|
||||
rprint(
|
||||
f"[green]✓[/green] 已更新 Agent [bold]{saved.name}[/bold]"
|
||||
f" 模式={MODE_DISPLAY.get(saved.mode, str(saved.mode))}"
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
"""auth 命令:管理企业认证信息"""
|
||||
"""auth 命令:管理企业认证信息
|
||||
|
||||
表现层:只负责参数解析、交互式输入、rich 格式化输出。
|
||||
业务逻辑委托给 services.auth_service。
|
||||
"""
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli import config
|
||||
from ekb_cli.services import auth_service
|
||||
|
||||
app = typer.Typer(help="管理企业认证")
|
||||
console = Console()
|
||||
@@ -17,6 +21,7 @@ def auth_add():
|
||||
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()
|
||||
@@ -28,16 +33,15 @@ def auth_add():
|
||||
|
||||
name = typer.prompt("企业名称(方便识别)", default=corp_id).strip()
|
||||
|
||||
config.add_corp(corp_id=corp_id, name=name, access_token=access_token, staff_id=staff_id)
|
||||
rprint(f"[green]✓[/green] 已添加企业 [bold]{name}[/bold] ({corp_id})")
|
||||
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():
|
||||
"""列出所有已添加的企业"""
|
||||
data = config.get_all()
|
||||
corps = data.get("corps", {})
|
||||
current = data.get("current")
|
||||
corps = auth_service.list_corps()
|
||||
|
||||
if not corps:
|
||||
rprint("[yellow]尚未添加任何企业,请先执行 `ekb auth add`[/yellow]")
|
||||
@@ -48,9 +52,9 @@ def auth_list():
|
||||
table.add_column("名称")
|
||||
table.add_column("corpId")
|
||||
|
||||
for corp_id, info in corps.items():
|
||||
marker = "[green]*[/green]" if corp_id == current else ""
|
||||
table.add_row(marker, info["name"], corp_id)
|
||||
for c in corps:
|
||||
marker = "[green]*[/green]" if c.is_current else ""
|
||||
table.add_row(marker, c.name, c.corp_id)
|
||||
|
||||
console.print(table)
|
||||
|
||||
@@ -58,27 +62,29 @@ def auth_list():
|
||||
@app.command("use")
|
||||
def auth_use(corp_id: str = typer.Argument(..., help="要切换的企业 corpId")):
|
||||
"""切换当前使用的企业"""
|
||||
from ekb_cli.errors import EkbError
|
||||
try:
|
||||
config.use_corp(corp_id)
|
||||
rprint(f"[green]✓[/green] 已切换到企业 [bold]{corp_id}[/bold]")
|
||||
except ValueError as e:
|
||||
rprint(f"[red]{e}[/red]")
|
||||
corp = auth_service.use_corp(corp_id)
|
||||
rprint(f"[green]✓[/green] 已切换到企业 [bold]{corp.name}[/bold] ({corp.corp_id})")
|
||||
except EkbError as e:
|
||||
rprint(f"[red]{e.message}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
@app.command("remove")
|
||||
def auth_remove(corp_id: str = typer.Argument(..., help="要删除的企业 corpId")):
|
||||
"""删除一个企业的认证信息"""
|
||||
config.remove_corp(corp_id)
|
||||
auth_service.remove_corp(corp_id)
|
||||
rprint(f"[green]✓[/green] 已删除企业 {corp_id}")
|
||||
|
||||
|
||||
@app.command("whoami")
|
||||
def auth_whoami():
|
||||
"""查看当前使用的企业"""
|
||||
corp = config.get_current_corp()
|
||||
corp_id = config.get_current_corp_id()
|
||||
if not corp:
|
||||
from ekb_cli.errors import NotLoggedInError
|
||||
try:
|
||||
corp = auth_service.whoami()
|
||||
rprint(f"当前企业:[bold]{corp.name}[/bold] ({corp.corp_id})")
|
||||
except NotLoggedInError:
|
||||
rprint("[yellow]未登录,请先执行 `ekb auth add`[/yellow]")
|
||||
raise typer.Exit(1)
|
||||
rprint(f"当前企业:[bold]{corp['name']}[/bold] ({corp_id})")
|
||||
@@ -0,0 +1,52 @@
|
||||
"""FastAPI 应用工厂
|
||||
|
||||
create_app() 创建并返回完整配置的 FastAPI 实例:
|
||||
- 注册 auth / agent / rule 三个路由组
|
||||
- 统一 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
|
||||
|
||||
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"])
|
||||
|
||||
# ── 统一异常处理: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
|
||||
@@ -0,0 +1,87 @@
|
||||
"""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()}
|
||||
@@ -0,0 +1,54 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,28 @@
|
||||
"""FastAPI 依赖注入:获取已认证的 EkbClient
|
||||
|
||||
用法:
|
||||
from ekb_cli.server.deps import ClientDep
|
||||
|
||||
@router.get("/foo")
|
||||
def my_route(client: ClientDep):
|
||||
...
|
||||
"""
|
||||
|
||||
from typing import Annotated, Generator
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from ekb_cli.api import EkbClient, get_client
|
||||
|
||||
|
||||
def _get_ekb_client() -> Generator[EkbClient, None, None]:
|
||||
"""FastAPI 依赖:获取快报 HTTP 客户端,请求结束后自动关闭连接"""
|
||||
client = get_client() # 未登录时抛出 NotLoggedInError → 被全局 handler 捕获
|
||||
try:
|
||||
yield client
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
# 类型别名,路由函数用 `client: ClientDep` 即可,简洁且支持类型推断
|
||||
ClientDep = Annotated[EkbClient, Depends(_get_ekb_client)]
|
||||
@@ -0,0 +1,57 @@
|
||||
"""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()
|
||||
Reference in new issue
Block a user