Compare commits
20 Commits
80d98b35a5
...
b7ec317d2c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7ec317d2c | ||
|
|
a0ca35c9dd | ||
|
|
77374121dd | ||
|
|
8b9d506893 | ||
|
|
5fdf96c3f5 | ||
|
|
9a5fad2b59 | ||
|
|
4d8d560d1f | ||
|
|
452ff45a5f | ||
|
|
bc12f6899a | ||
|
|
8cce2283f7 | ||
|
|
15450ca895 | ||
|
|
a66b675675 | ||
|
|
d760b9ca10 | ||
|
|
a0d59b1947 | ||
|
|
900430d93e | ||
|
|
94bf387aee | ||
|
|
00a08c9f9b | ||
|
|
a99a3df9dd | ||
|
|
fec64af565 | ||
|
|
a2f8112d69 |
1
.claude/worktrees/saas-backend
Submodule
1
.claude/worktrees/saas-backend
Submodule
Submodule .claude/worktrees/saas-backend added at 4d8d560d1f
4
.gitignore
vendored
4
.gitignore
vendored
@@ -12,6 +12,10 @@ build/
|
|||||||
.env.local
|
.env.local
|
||||||
.env.*.local
|
.env.*.local
|
||||||
|
|
||||||
|
# SaaS config (contains database credentials)
|
||||||
|
saas-config.toml
|
||||||
|
!saas-config.toml.example
|
||||||
|
|
||||||
# Logs
|
# Logs
|
||||||
logs/
|
logs/
|
||||||
*.log
|
*.log
|
||||||
|
|||||||
30
CLAUDE.md
30
CLAUDE.md
@@ -37,16 +37,20 @@ ZCLAW/
|
|||||||
│ ├── zclaw-skills/ # 技能系统 (SKILL.md解析, 执行器)
|
│ ├── zclaw-skills/ # 技能系统 (SKILL.md解析, 执行器)
|
||||||
│ ├── zclaw-hands/ # 自主能力 (Hand/Trigger 注册管理)
|
│ ├── zclaw-hands/ # 自主能力 (Hand/Trigger 注册管理)
|
||||||
│ ├── zclaw-channels/ # 通道适配器 (仅 ConsoleChannel 测试适配器)
|
│ ├── zclaw-channels/ # 通道适配器 (仅 ConsoleChannel 测试适配器)
|
||||||
│ └── zclaw-protocols/ # 协议支持 (MCP, A2A)
|
│ ├── zclaw-protocols/ # 协议支持 (MCP, A2A)
|
||||||
|
│ └── zclaw-saas/ # SaaS 后端 (账号, 模型配置, 中转, 配置同步)
|
||||||
|
├── admin/ # Next.js 管理后台
|
||||||
├── desktop/ # Tauri 桌面应用
|
├── desktop/ # Tauri 桌面应用
|
||||||
│ ├── src/
|
│ ├── src/
|
||||||
│ │ ├── components/ # React UI 组件
|
│ │ ├── components/ # React UI 组件 (含 SaaS 集成)
|
||||||
│ │ ├── store/ # Zustand 状态管理
|
│ │ ├── store/ # Zustand 状态管理 (含 saasStore)
|
||||||
│ │ └── lib/ # 客户端通信 / 工具函数
|
│ │ └── lib/ # 客户端通信 / 工具函数 (含 saas-client)
|
||||||
│ └── src-tauri/ # Tauri Rust 后端 (集成 Kernel)
|
│ └── src-tauri/ # Tauri Rust 后端 (集成 Kernel)
|
||||||
├── skills/ # SKILL.md 技能定义
|
├── skills/ # SKILL.md 技能定义
|
||||||
├── hands/ # HAND.toml 自主能力配置
|
├── hands/ # HAND.toml 自主能力配置
|
||||||
├── config/ # TOML 配置文件
|
├── config/ # TOML 配置文件
|
||||||
|
├── saas-config.toml # SaaS 后端配置 (PostgreSQL 连接等)
|
||||||
|
├── docker-compose.yml # PostgreSQL 容器配置
|
||||||
├── docs/ # 架构文档和知识库
|
├── docs/ # 架构文档和知识库
|
||||||
└── tests/ # Vitest 回归测试
|
└── tests/ # Vitest 回归测试
|
||||||
```
|
```
|
||||||
@@ -66,7 +70,9 @@ ZCLAW/
|
|||||||
| 桌面框架 | Tauri 2.x |
|
| 桌面框架 | Tauri 2.x |
|
||||||
| 样式方案 | Tailwind CSS |
|
| 样式方案 | Tailwind CSS |
|
||||||
| 配置格式 | TOML |
|
| 配置格式 | TOML |
|
||||||
| 后端核心 | Rust Workspace (8 crates) |
|
| 后端核心 | Rust Workspace (9 crates) |
|
||||||
|
| SaaS 后端 | Axum + PostgreSQL (zclaw-saas) |
|
||||||
|
| 管理后台 | Next.js (admin/) |
|
||||||
|
|
||||||
### 2.3 Crate 依赖关系
|
### 2.3 Crate 依赖关系
|
||||||
|
|
||||||
@@ -79,6 +85,8 @@ zclaw-runtime (→ types, memory)
|
|||||||
↑
|
↑
|
||||||
zclaw-kernel (→ types, memory, runtime)
|
zclaw-kernel (→ types, memory, runtime)
|
||||||
↑
|
↑
|
||||||
|
zclaw-saas (→ types, 独立运行于 8080 端口)
|
||||||
|
↑
|
||||||
desktop/src-tauri (→ kernel, skills, hands, channels, protocols)
|
desktop/src-tauri (→ kernel, skills, hands, channels, protocols)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -260,6 +268,18 @@ docs/
|
|||||||
- **面向未来** - 文档要帮助未来的开发者快速理解
|
- **面向未来** - 文档要帮助未来的开发者快速理解
|
||||||
- **中文优先** - 所有面向用户的文档使用中文
|
- **中文优先** - 所有面向用户的文档使用中文
|
||||||
|
|
||||||
|
### 8.3 完成工作后的文档同步(强制)
|
||||||
|
|
||||||
|
每次完成功能实现、架构变更、问题修复后,**必须**同步更新以下文档:
|
||||||
|
|
||||||
|
1. **CLAUDE.md** — 如果涉及项目结构、技术栈、工作流程、命令的变化
|
||||||
|
2. **docs/features/** — 如果涉及新功能、功能变更、功能状态更新
|
||||||
|
3. **docs/knowledge-base/** — 如果涉及新知识、故障排查经验、配置说明
|
||||||
|
4. **saas-config.toml 注释** — 如果涉及 SaaS 配置项变更
|
||||||
|
5. **CHANGELOG** — 如果涉及对外可见的行为变化
|
||||||
|
|
||||||
|
**执行时机:** 代码编译通过且验证成功后,在标记任务完成之前,立即执行文档更新。文档更新是任务完成的必要条件,不是可选步骤。
|
||||||
|
|
||||||
***
|
***
|
||||||
|
|
||||||
## 9. 常见问题排查
|
## 9. 常见问题排查
|
||||||
|
|||||||
1274
Cargo.lock
generated
1274
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
19
Cargo.toml
19
Cargo.toml
@@ -15,6 +15,8 @@ members = [
|
|||||||
"crates/zclaw-growth",
|
"crates/zclaw-growth",
|
||||||
# Desktop Application
|
# Desktop Application
|
||||||
"desktop/src-tauri",
|
"desktop/src-tauri",
|
||||||
|
# SaaS Backend
|
||||||
|
"crates/zclaw-saas",
|
||||||
]
|
]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
@@ -55,7 +57,7 @@ chrono = { version = "0.4", features = ["serde"] }
|
|||||||
uuid = { version = "1", features = ["v4", "v5", "serde"] }
|
uuid = { version = "1", features = ["v4", "v5", "serde"] }
|
||||||
|
|
||||||
# Database
|
# Database
|
||||||
sqlx = { version = "0.7", features = ["runtime-tokio", "sqlite"] }
|
sqlx = { version = "0.7", features = ["runtime-tokio", "sqlite", "postgres"] }
|
||||||
libsqlite3-sys = { version = "0.27", features = ["bundled"] }
|
libsqlite3-sys = { version = "0.27", features = ["bundled"] }
|
||||||
|
|
||||||
# HTTP client (for LLM drivers)
|
# HTTP client (for LLM drivers)
|
||||||
@@ -92,9 +94,23 @@ regex = "1"
|
|||||||
# Shell parsing
|
# Shell parsing
|
||||||
shlex = "1"
|
shlex = "1"
|
||||||
|
|
||||||
|
# WASM runtime
|
||||||
|
wasmtime = { version = "43", default-features = false, features = ["cranelift"] }
|
||||||
|
wasmtime-wasi = { version = "43" }
|
||||||
|
|
||||||
# Testing
|
# Testing
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
|
||||||
|
# SaaS dependencies
|
||||||
|
axum = { version = "0.7", features = ["macros"] }
|
||||||
|
axum-extra = { version = "0.9", features = ["typed-header"] }
|
||||||
|
tower = { version = "0.4", features = ["util"] }
|
||||||
|
tower-http = { version = "0.5", features = ["cors", "trace", "limit", "timeout"] }
|
||||||
|
jsonwebtoken = "9"
|
||||||
|
argon2 = "0.5"
|
||||||
|
totp-rs = "5"
|
||||||
|
hex = "0.4"
|
||||||
|
|
||||||
# Internal crates
|
# Internal crates
|
||||||
zclaw-types = { path = "crates/zclaw-types" }
|
zclaw-types = { path = "crates/zclaw-types" }
|
||||||
zclaw-memory = { path = "crates/zclaw-memory" }
|
zclaw-memory = { path = "crates/zclaw-memory" }
|
||||||
@@ -106,6 +122,7 @@ zclaw-channels = { path = "crates/zclaw-channels" }
|
|||||||
zclaw-protocols = { path = "crates/zclaw-protocols" }
|
zclaw-protocols = { path = "crates/zclaw-protocols" }
|
||||||
zclaw-pipeline = { path = "crates/zclaw-pipeline" }
|
zclaw-pipeline = { path = "crates/zclaw-pipeline" }
|
||||||
zclaw-growth = { path = "crates/zclaw-growth" }
|
zclaw-growth = { path = "crates/zclaw-growth" }
|
||||||
|
zclaw-saas = { path = "crates/zclaw-saas" }
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
lto = true
|
lto = true
|
||||||
|
|||||||
2
admin/.gitignore
vendored
Normal file
2
admin/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
.next/
|
||||||
|
node_modules/
|
||||||
5
admin/next-env.d.ts
vendored
Normal file
5
admin/next-env.d.ts
vendored
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
/// <reference types="next" />
|
||||||
|
/// <reference types="next/image-types/global" />
|
||||||
|
|
||||||
|
// NOTE: This file should not be edited
|
||||||
|
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
|
||||||
13
admin/next.config.js
Normal file
13
admin/next.config.js
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
/** @type {import('next').NextConfig} */
|
||||||
|
const nextConfig = {
|
||||||
|
async rewrites() {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
source: '/api/:path*',
|
||||||
|
destination: 'http://localhost:8080/api/:path*',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = nextConfig
|
||||||
38
admin/package.json
Normal file
38
admin/package.json
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"name": "zclaw-admin",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next dev",
|
||||||
|
"build": "next build",
|
||||||
|
"start": "next start",
|
||||||
|
"lint": "next lint"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/react-dialog": "^1.1.14",
|
||||||
|
"@radix-ui/react-select": "^2.2.5",
|
||||||
|
"@radix-ui/react-separator": "^1.1.7",
|
||||||
|
"@radix-ui/react-switch": "^1.2.5",
|
||||||
|
"@radix-ui/react-tabs": "^1.1.12",
|
||||||
|
"@radix-ui/react-tooltip": "^1.2.7",
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"lucide-react": "^0.484.0",
|
||||||
|
"next": "14.2.29",
|
||||||
|
"react": "^18.3.1",
|
||||||
|
"react-dom": "^18.3.1",
|
||||||
|
"recharts": "^2.15.3",
|
||||||
|
"swr": "^2.4.1",
|
||||||
|
"tailwind-merge": "^3.0.2"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^20.17.19",
|
||||||
|
"@types/react": "^18.3.18",
|
||||||
|
"@types/react-dom": "^18.3.5",
|
||||||
|
"autoprefixer": "^10.4.20",
|
||||||
|
"postcss": "^8.5.3",
|
||||||
|
"tailwindcss": "^3.4.17",
|
||||||
|
"typescript": "^5.7.3"
|
||||||
|
},
|
||||||
|
"packageManager": "pnpm@10.30.2"
|
||||||
|
}
|
||||||
2200
admin/pnpm-lock.yaml
generated
Normal file
2200
admin/pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
6
admin/postcss.config.js
Normal file
6
admin/postcss.config.js
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
module.exports = {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
373
admin/src/app/(dashboard)/accounts/page.tsx
Normal file
373
admin/src/app/(dashboard)/accounts/page.tsx
Normal file
@@ -0,0 +1,373 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import useSWR from 'swr'
|
||||||
|
import {
|
||||||
|
Search,
|
||||||
|
Plus,
|
||||||
|
Loader2,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
Pencil,
|
||||||
|
Ban,
|
||||||
|
CheckCircle2,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogFooter,
|
||||||
|
DialogDescription,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { ApiRequestError } from '@/lib/api-client'
|
||||||
|
import { formatDate, getSwrErrorMessage } from '@/lib/utils'
|
||||||
|
import { ErrorBanner, EmptyState } from '@/components/ui/state'
|
||||||
|
import { TableSkeleton } from '@/components/ui/skeleton'
|
||||||
|
import { useDebounce } from '@/hooks/use-debounce'
|
||||||
|
import type { AccountPublic } from '@/lib/types'
|
||||||
|
|
||||||
|
const PAGE_SIZE = 20
|
||||||
|
|
||||||
|
const roleLabels: Record<string, string> = {
|
||||||
|
super_admin: '超级管理员',
|
||||||
|
admin: '管理员',
|
||||||
|
user: '普通用户',
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusColors: Record<string, 'success' | 'destructive' | 'warning'> = {
|
||||||
|
active: 'success',
|
||||||
|
disabled: 'destructive',
|
||||||
|
suspended: 'warning',
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusLabels: Record<string, string> = {
|
||||||
|
active: '正常',
|
||||||
|
disabled: '已禁用',
|
||||||
|
suspended: '已暂停',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AccountsPage() {
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [search, setSearch] = useState('')
|
||||||
|
const [roleFilter, setRoleFilter] = useState<string>('all')
|
||||||
|
const [statusFilter, setStatusFilter] = useState<string>('all')
|
||||||
|
const [mutationError, setMutationError] = useState('')
|
||||||
|
|
||||||
|
const debouncedSearch = useDebounce(search, 300)
|
||||||
|
|
||||||
|
const { data, error: swrError, isLoading, mutate } = useSWR(
|
||||||
|
['accounts', page, debouncedSearch, roleFilter, statusFilter],
|
||||||
|
() => {
|
||||||
|
const params: Record<string, unknown> = { page, page_size: PAGE_SIZE }
|
||||||
|
if (debouncedSearch.trim()) params.search = debouncedSearch.trim()
|
||||||
|
if (roleFilter !== 'all') params.role = roleFilter
|
||||||
|
if (statusFilter !== 'all') params.status = statusFilter
|
||||||
|
return api.accounts.list(params)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
const accounts = data?.items ?? []
|
||||||
|
const total = data?.total ?? 0
|
||||||
|
const error = getSwrErrorMessage(swrError) || mutationError
|
||||||
|
|
||||||
|
// 编辑 Dialog
|
||||||
|
const [editTarget, setEditTarget] = useState<AccountPublic | null>(null)
|
||||||
|
const [editForm, setEditForm] = useState({ display_name: '', email: '', role: 'user' })
|
||||||
|
const [editSaving, setEditSaving] = useState(false)
|
||||||
|
|
||||||
|
// 确认 Dialog
|
||||||
|
const [confirmTarget, setConfirmTarget] = useState<{ id: string; action: string; status: string } | null>(null)
|
||||||
|
const [confirmSaving, setConfirmSaving] = useState(false)
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
|
||||||
|
|
||||||
|
function openEditDialog(account: AccountPublic) {
|
||||||
|
setEditTarget(account)
|
||||||
|
setEditForm({
|
||||||
|
display_name: account.display_name,
|
||||||
|
email: account.email,
|
||||||
|
role: account.role,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleEditSave() {
|
||||||
|
if (!editTarget) return
|
||||||
|
setEditSaving(true)
|
||||||
|
try {
|
||||||
|
await api.accounts.update(editTarget.id, {
|
||||||
|
display_name: editForm.display_name,
|
||||||
|
email: editForm.email,
|
||||||
|
role: editForm.role as AccountPublic['role'],
|
||||||
|
})
|
||||||
|
setEditTarget(null)
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) {
|
||||||
|
setMutationError(err.body.message)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setEditSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openConfirmDialog(account: AccountPublic) {
|
||||||
|
const newStatus = account.status === 'active' ? 'disabled' : 'active'
|
||||||
|
setConfirmTarget({
|
||||||
|
id: account.id,
|
||||||
|
action: newStatus === 'disabled' ? '禁用' : '启用',
|
||||||
|
status: newStatus,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleConfirmSave() {
|
||||||
|
if (!confirmTarget) return
|
||||||
|
setConfirmSaving(true)
|
||||||
|
try {
|
||||||
|
await api.accounts.updateStatus(confirmTarget.id, {
|
||||||
|
status: confirmTarget.status as AccountPublic['status'],
|
||||||
|
})
|
||||||
|
setConfirmTarget(null)
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) {
|
||||||
|
setMutationError(err.body.message)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setConfirmSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* 搜索和筛选 */}
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
|
<div className="relative flex-1 min-w-[200px] max-w-sm">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
placeholder="搜索用户名 / 邮箱 / 显示名..."
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => { setSearch(e.target.value); setPage(1) }}
|
||||||
|
className="pl-10"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Select value={roleFilter} onValueChange={(v) => { setRoleFilter(v); setPage(1) }}>
|
||||||
|
<SelectTrigger className="w-[140px]">
|
||||||
|
<SelectValue placeholder="角色筛选" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">全部角色</SelectItem>
|
||||||
|
<SelectItem value="super_admin">超级管理员</SelectItem>
|
||||||
|
<SelectItem value="admin">管理员</SelectItem>
|
||||||
|
<SelectItem value="user">普通用户</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<Select value={statusFilter} onValueChange={(v) => { setStatusFilter(v); setPage(1) }}>
|
||||||
|
<SelectTrigger className="w-[140px]">
|
||||||
|
<SelectValue placeholder="状态筛选" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">全部状态</SelectItem>
|
||||||
|
<SelectItem value="active">正常</SelectItem>
|
||||||
|
<SelectItem value="disabled">已禁用</SelectItem>
|
||||||
|
<SelectItem value="suspended">已暂停</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 错误提示 */}
|
||||||
|
{error && <ErrorBanner message={error} onDismiss={() => { setMutationError('') }} />}
|
||||||
|
|
||||||
|
{/* 表格 */}
|
||||||
|
{isLoading ? (
|
||||||
|
<TableSkeleton rows={6} cols={7} />
|
||||||
|
) : error ? null : accounts.length === 0 ? (
|
||||||
|
<EmptyState />
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>用户名</TableHead>
|
||||||
|
<TableHead>邮箱</TableHead>
|
||||||
|
<TableHead>显示名</TableHead>
|
||||||
|
<TableHead>角色</TableHead>
|
||||||
|
<TableHead>状态</TableHead>
|
||||||
|
<TableHead>创建时间</TableHead>
|
||||||
|
<TableHead className="text-right">操作</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{accounts.map((account) => (
|
||||||
|
<TableRow key={account.id}>
|
||||||
|
<TableCell className="font-medium">{account.username}</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">{account.email}</TableCell>
|
||||||
|
<TableCell>{account.display_name || '-'}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={account.role === 'super_admin' ? 'default' : account.role === 'admin' ? 'info' : 'secondary'}>
|
||||||
|
{roleLabels[account.role] || account.role}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={statusColors[account.status] || 'secondary'}>
|
||||||
|
<span className="mr-1 inline-block h-1.5 w-1.5 rounded-full bg-current" />
|
||||||
|
{statusLabels[account.status] || account.status}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{formatDate(account.created_at)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<div className="flex items-center justify-end gap-1">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => openEditDialog(account)}
|
||||||
|
title="编辑"
|
||||||
|
>
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => openConfirmDialog(account)}
|
||||||
|
title={account.status === 'active' ? '禁用' : '启用'}
|
||||||
|
>
|
||||||
|
{account.status === 'active' ? (
|
||||||
|
<Ban className="h-4 w-4 text-destructive" />
|
||||||
|
) : (
|
||||||
|
<CheckCircle2 className="h-4 w-4 text-green-400" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
|
||||||
|
{/* 分页 */}
|
||||||
|
<div className="flex items-center justify-between text-sm">
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
第 {page} 页 / 共 {totalPages} 页 ({total} 条)
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={page <= 1}
|
||||||
|
onClick={() => setPage(page - 1)}
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-4 w-4 mr-1" />
|
||||||
|
上一页
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={page >= totalPages}
|
||||||
|
onClick={() => setPage(page + 1)}
|
||||||
|
>
|
||||||
|
下一页
|
||||||
|
<ChevronRight className="h-4 w-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 编辑 Dialog */}
|
||||||
|
<Dialog open={!!editTarget} onOpenChange={() => setEditTarget(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>编辑账号</DialogTitle>
|
||||||
|
<DialogDescription>修改账号信息</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>显示名</Label>
|
||||||
|
<Input
|
||||||
|
value={editForm.display_name}
|
||||||
|
onChange={(e) => setEditForm({ ...editForm, display_name: e.target.value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>邮箱</Label>
|
||||||
|
<Input
|
||||||
|
type="email"
|
||||||
|
value={editForm.email}
|
||||||
|
onChange={(e) => setEditForm({ ...editForm, email: e.target.value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>角色</Label>
|
||||||
|
<Select value={editForm.role} onValueChange={(v) => setEditForm({ ...editForm, role: v })}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="user">普通用户</SelectItem>
|
||||||
|
<SelectItem value="admin">管理员</SelectItem>
|
||||||
|
<SelectItem value="super_admin">超级管理员</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setEditTarget(null)}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button onClick={handleEditSave} disabled={editSaving}>
|
||||||
|
{editSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
保存
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* 确认 Dialog */}
|
||||||
|
<Dialog open={!!confirmTarget} onOpenChange={() => setConfirmTarget(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>确认{confirmTarget?.action}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
确定要{confirmTarget?.action}该账号吗?此操作将立即生效。
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setConfirmTarget(null)}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={confirmTarget?.status === 'disabled' ? 'destructive' : 'default'}
|
||||||
|
onClick={handleConfirmSave}
|
||||||
|
disabled={confirmSaving}
|
||||||
|
>
|
||||||
|
{confirmSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
确认{confirmTarget?.action}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
290
admin/src/app/(dashboard)/agent-templates/page.tsx
Normal file
290
admin/src/app/(dashboard)/agent-templates/page.tsx
Normal file
@@ -0,0 +1,290 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import useSWR from 'swr'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import type { AgentTemplate } from '@/lib/types'
|
||||||
|
import { ErrorBanner, EmptyState } from '@/components/ui/state'
|
||||||
|
import { TableSkeleton } from '@/components/ui/skeleton'
|
||||||
|
|
||||||
|
export default function AgentTemplatesPage() {
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [showCreate, setShowCreate] = useState(false)
|
||||||
|
const [editingId, setEditingId] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const { data, isLoading, mutate } = useSWR(
|
||||||
|
['agentTemplates.list', page],
|
||||||
|
() => api.agentTemplates.list({ page, page_size: 50 }),
|
||||||
|
)
|
||||||
|
|
||||||
|
const templates = data?.items ?? []
|
||||||
|
const total = data?.total ?? 0
|
||||||
|
|
||||||
|
const handleCreate = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault()
|
||||||
|
const fd = new FormData(e.currentTarget)
|
||||||
|
try {
|
||||||
|
const tools = (fd.get('tools') as string || '').split(',').map(s => s.trim()).filter(Boolean)
|
||||||
|
const capabilities = (fd.get('capabilities') as string || '').split(',').map(s => s.trim()).filter(Boolean)
|
||||||
|
await api.agentTemplates.create({
|
||||||
|
name: fd.get('name') as string,
|
||||||
|
description: (fd.get('description') as string) || undefined,
|
||||||
|
category: (fd.get('category') as string) || 'general',
|
||||||
|
model: (fd.get('model') as string) || undefined,
|
||||||
|
system_prompt: (fd.get('system_prompt') as string) || undefined,
|
||||||
|
tools: tools.length > 0 ? tools : undefined,
|
||||||
|
capabilities: capabilities.length > 0 ? capabilities : undefined,
|
||||||
|
temperature: (fd.get('temperature') as string) ? parseFloat(fd.get('temperature') as string) : undefined,
|
||||||
|
max_tokens: (fd.get('max_tokens') as string) ? parseInt(fd.get('max_tokens') as string, 10) : undefined,
|
||||||
|
visibility: (fd.get('visibility') as string) || 'public',
|
||||||
|
})
|
||||||
|
setShowCreate(false)
|
||||||
|
mutate()
|
||||||
|
} catch {
|
||||||
|
setError('创建失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleArchive = async (id: string, name: string) => {
|
||||||
|
if (!confirm(`确认归档模板 "${name}"?`)) return
|
||||||
|
try {
|
||||||
|
await api.agentTemplates.archive(id)
|
||||||
|
mutate()
|
||||||
|
} catch {
|
||||||
|
setError('归档失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusBadge = (status: string) => {
|
||||||
|
const colors: Record<string, string> = {
|
||||||
|
active: 'bg-emerald-500/20 text-emerald-400',
|
||||||
|
archived: 'bg-zinc-500/20 text-zinc-400',
|
||||||
|
}
|
||||||
|
return <span className={`px-2 py-0.5 text-xs rounded-full ${colors[status] || colors.archived}`}>{status}</span>
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceBadge = (source: string) => {
|
||||||
|
const colors: Record<string, string> = {
|
||||||
|
builtin: 'bg-blue-500/20 text-blue-400',
|
||||||
|
custom: 'bg-purple-500/20 text-purple-400',
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<span className={`px-2 py-0.5 text-xs rounded-full ${colors[source] || ''}`}>
|
||||||
|
{source === 'builtin' ? '内置' : '自定义'}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-white">Agent 配置模板</h1>
|
||||||
|
<p className="text-sm text-zinc-400 mt-1">管理 Agent 配置模板,支持团队共享和一键复用</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreate(true)}
|
||||||
|
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm"
|
||||||
|
>
|
||||||
|
+ 新建模板
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <ErrorBanner message={error} onDismiss={() => setError('')} />}
|
||||||
|
|
||||||
|
<div className="bg-zinc-900 rounded-xl border border-zinc-800 overflow-hidden">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-zinc-800">
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">名称</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">分类</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">来源</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">模型</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">工具数</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">可见性</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">状态</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">更新时间</th>
|
||||||
|
<th className="text-right px-4 py-3 text-zinc-400 font-medium">操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{isLoading ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={9}>
|
||||||
|
<TableSkeleton rows={5} cols={9} hasToolbar={false} />
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : templates.length === 0 ? (
|
||||||
|
<tr><td colSpan={9}><EmptyState message="暂无 Agent 模板" /></td></tr>
|
||||||
|
) : (
|
||||||
|
templates.map(t => (
|
||||||
|
<tr key={t.id} className="border-b border-zinc-800/50 hover:bg-zinc-800/30">
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<div>
|
||||||
|
<span className="text-white font-medium">{t.name}</span>
|
||||||
|
{t.description && (
|
||||||
|
<p className="text-xs text-zinc-500 mt-0.5 truncate max-w-[200px]">{t.description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-zinc-400">{t.category}</td>
|
||||||
|
<td className="px-4 py-3">{sourceBadge(t.source)}</td>
|
||||||
|
<td className="px-4 py-3 text-zinc-300 font-mono text-xs">{t.model || '-'}</td>
|
||||||
|
<td className="px-4 py-3 text-zinc-400">{t.tools.length}</td>
|
||||||
|
<td className="px-4 py-3 text-zinc-400">{t.visibility}</td>
|
||||||
|
<td className="px-4 py-3">{statusBadge(t.status)}</td>
|
||||||
|
<td className="px-4 py-3 text-zinc-500 text-xs">
|
||||||
|
{new Date(t.updated_at).toLocaleString('zh-CN')}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-right">
|
||||||
|
<button
|
||||||
|
onClick={() => setEditingId(editingId === t.id ? null : t.id)}
|
||||||
|
className="text-zinc-400 hover:text-white mr-2"
|
||||||
|
>
|
||||||
|
详情
|
||||||
|
</button>
|
||||||
|
{t.source === 'custom' && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleArchive(t.id, t.name)}
|
||||||
|
className="text-red-400 hover:text-red-300"
|
||||||
|
>
|
||||||
|
归档
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<div className="px-4 py-2 text-xs text-zinc-500 border-t border-zinc-800">
|
||||||
|
共 {total} 个模板
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 展开详情 */}
|
||||||
|
{editingId && (() => {
|
||||||
|
const t = templates.find(t => t.id === editingId)
|
||||||
|
if (!t) return null
|
||||||
|
return (
|
||||||
|
<div className="bg-zinc-900 rounded-xl border border-zinc-800 p-4">
|
||||||
|
<div className="flex items-center justify-between mb-3">
|
||||||
|
<h2 className="text-lg font-semibold text-white">{t.name} — 详情</h2>
|
||||||
|
<button onClick={() => setEditingId(null)} className="text-zinc-400 hover:text-white text-sm">关闭</button>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||||
|
<div>
|
||||||
|
<span className="text-zinc-500">分类:</span>
|
||||||
|
<span className="text-zinc-300">{t.category}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-zinc-500">模型:</span>
|
||||||
|
<span className="text-zinc-300 font-mono">{t.model || '未指定'}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-zinc-500">温度:</span>
|
||||||
|
<span className="text-zinc-300">{t.temperature?.toFixed(2) || '默认'}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-zinc-500">最大 Token:</span>
|
||||||
|
<span className="text-zinc-300">{t.max_tokens || '未限制'}</span>
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2">
|
||||||
|
<span className="text-zinc-500">工具:</span>
|
||||||
|
<div className="flex flex-wrap gap-1 mt-1">
|
||||||
|
{t.tools.length > 0 ? t.tools.map(tool => (
|
||||||
|
<span key={tool} className="px-2 py-0.5 bg-zinc-800 rounded text-xs text-zinc-300">{tool}</span>
|
||||||
|
)) : <span className="text-zinc-600">无</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2">
|
||||||
|
<span className="text-zinc-500">能力:</span>
|
||||||
|
<div className="flex flex-wrap gap-1 mt-1">
|
||||||
|
{t.capabilities.length > 0 ? t.capabilities.map(cap => (
|
||||||
|
<span key={cap} className="px-2 py-0.5 bg-blue-500/10 rounded text-xs text-blue-400">{cap}</span>
|
||||||
|
)) : <span className="text-zinc-600">无</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{t.system_prompt && (
|
||||||
|
<div className="col-span-2">
|
||||||
|
<span className="text-zinc-500">系统提示词:</span>
|
||||||
|
<pre className="text-xs text-zinc-400 bg-zinc-800/50 rounded p-2 mt-1 overflow-x-auto max-h-32">
|
||||||
|
{t.system_prompt.substring(0, 500)}{t.system_prompt.length > 500 ? '...' : ''}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})()}
|
||||||
|
|
||||||
|
{/* Create Modal */}
|
||||||
|
{showCreate && (
|
||||||
|
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
|
||||||
|
<form onSubmit={handleCreate} className="bg-zinc-900 rounded-xl border border-zinc-700 p-6 w-full max-w-lg space-y-4 max-h-[80vh] overflow-y-auto">
|
||||||
|
<h2 className="text-lg font-semibold text-white">新建 Agent 模板</h2>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">名称 *</label>
|
||||||
|
<input name="name" required className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm" placeholder="my_agent" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">描述</label>
|
||||||
|
<input name="description" className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm" placeholder="可选" />
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">分类</label>
|
||||||
|
<select name="category" className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm">
|
||||||
|
<option value="general">通用</option>
|
||||||
|
<option value="coding">编程</option>
|
||||||
|
<option value="research">研究</option>
|
||||||
|
<option value="creative">创意</option>
|
||||||
|
<option value="assistant">助手</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">模型</label>
|
||||||
|
<input name="model" className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm" placeholder="如 glm-4-plus" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">系统提示词</label>
|
||||||
|
<textarea name="system_prompt" rows={4} className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm font-mono" placeholder="Agent 系统提示词" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">工具(逗号分隔)</label>
|
||||||
|
<input name="tools" className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm" placeholder="browser, file_system, code_execute" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">能力(逗号分隔)</label>
|
||||||
|
<input name="capabilities" className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm" placeholder="streaming, vision, function_calling" />
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-3 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">温度</label>
|
||||||
|
<input name="temperature" type="number" step="0.1" className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm" placeholder="默认" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">最大 Token</label>
|
||||||
|
<input name="max_tokens" type="number" className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm" placeholder="不限" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">可见性</label>
|
||||||
|
<select name="visibility" className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm">
|
||||||
|
<option value="public">公开</option>
|
||||||
|
<option value="team">团队</option>
|
||||||
|
<option value="private">私有</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 justify-end">
|
||||||
|
<button type="button" onClick={() => setShowCreate(false)} className="px-4 py-2 bg-zinc-700 text-white rounded-lg hover:bg-zinc-600 text-sm">取消</button>
|
||||||
|
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm">创建</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
332
admin/src/app/(dashboard)/api-keys/page.tsx
Normal file
332
admin/src/app/(dashboard)/api-keys/page.tsx
Normal file
@@ -0,0 +1,332 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import useSWR from 'swr'
|
||||||
|
import {
|
||||||
|
Plus,
|
||||||
|
Loader2,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
Trash2,
|
||||||
|
Copy,
|
||||||
|
Check,
|
||||||
|
AlertTriangle,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogFooter,
|
||||||
|
DialogDescription,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { ErrorBanner, EmptyState } from '@/components/ui/state'
|
||||||
|
import { ApiRequestError } from '@/lib/api-client'
|
||||||
|
import { formatDate, getSwrErrorMessage } from '@/lib/utils'
|
||||||
|
import { TableSkeleton } from '@/components/ui/skeleton'
|
||||||
|
import type { TokenInfo } from '@/lib/types'
|
||||||
|
|
||||||
|
const PAGE_SIZE = 20
|
||||||
|
|
||||||
|
const allPermissions = [
|
||||||
|
{ key: 'chat', label: '对话' },
|
||||||
|
{ key: 'relay', label: '中转' },
|
||||||
|
{ key: 'admin', label: '管理' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export default function ApiKeysPage() {
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [mutationError, setMutationError] = useState('')
|
||||||
|
|
||||||
|
const { data, error: swrError, isLoading, mutate } = useSWR(
|
||||||
|
['tokens', page],
|
||||||
|
() => api.tokens.list({ page, page_size: PAGE_SIZE }),
|
||||||
|
)
|
||||||
|
|
||||||
|
const tokens = data?.items ?? []
|
||||||
|
const total = data?.total ?? 0
|
||||||
|
const error = getSwrErrorMessage(swrError) || mutationError
|
||||||
|
|
||||||
|
// 创建 Dialog
|
||||||
|
const [createOpen, setCreateOpen] = useState(false)
|
||||||
|
const [createForm, setCreateForm] = useState({ name: '', expires_days: '', permissions: ['chat'] as string[] })
|
||||||
|
const [creating, setCreating] = useState(false)
|
||||||
|
|
||||||
|
// 创建成功显示 token
|
||||||
|
const [createdToken, setCreatedToken] = useState<TokenInfo | null>(null)
|
||||||
|
const [copied, setCopied] = useState(false)
|
||||||
|
|
||||||
|
// 撤销确认
|
||||||
|
const [revokeTarget, setRevokeTarget] = useState<TokenInfo | null>(null)
|
||||||
|
const [revoking, setRevoking] = useState(false)
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
|
||||||
|
|
||||||
|
function togglePermission(perm: string) {
|
||||||
|
setCreateForm((prev) => ({
|
||||||
|
...prev,
|
||||||
|
permissions: prev.permissions.includes(perm)
|
||||||
|
? prev.permissions.filter((p) => p !== perm)
|
||||||
|
: [...prev.permissions, perm],
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleCreate() {
|
||||||
|
if (!createForm.name.trim() || createForm.permissions.length === 0) return
|
||||||
|
setCreating(true)
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
name: createForm.name.trim(),
|
||||||
|
expires_days: createForm.expires_days ? parseInt(createForm.expires_days, 10) : undefined,
|
||||||
|
permissions: createForm.permissions,
|
||||||
|
}
|
||||||
|
const res = await api.tokens.create(payload)
|
||||||
|
setCreateOpen(false)
|
||||||
|
setCreatedToken(res)
|
||||||
|
setCreateForm({ name: '', expires_days: '', permissions: ['chat'] })
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) setMutationError(err.body.message)
|
||||||
|
} finally {
|
||||||
|
setCreating(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRevoke() {
|
||||||
|
if (!revokeTarget) return
|
||||||
|
setRevoking(true)
|
||||||
|
try {
|
||||||
|
await api.tokens.revoke(revokeTarget.id)
|
||||||
|
setRevokeTarget(null)
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) setMutationError(err.body.message)
|
||||||
|
} finally {
|
||||||
|
setRevoking(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyToken() {
|
||||||
|
if (!createdToken?.token) return
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(createdToken.token)
|
||||||
|
setCopied(true)
|
||||||
|
setTimeout(() => setCopied(false), 2000)
|
||||||
|
} catch {
|
||||||
|
// Fallback
|
||||||
|
const textarea = document.createElement('textarea')
|
||||||
|
textarea.value = createdToken.token
|
||||||
|
document.body.appendChild(textarea)
|
||||||
|
textarea.select()
|
||||||
|
document.execCommand('copy')
|
||||||
|
document.body.removeChild(textarea)
|
||||||
|
setCopied(true)
|
||||||
|
setTimeout(() => setCopied(false), 2000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div />
|
||||||
|
<Button onClick={() => setCreateOpen(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
新建密钥
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <ErrorBanner message={error} onDismiss={() => setMutationError('')} />}
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<TableSkeleton rows={6} cols={7} />
|
||||||
|
) : error ? null : tokens.length === 0 ? (
|
||||||
|
<EmptyState />
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>名称</TableHead>
|
||||||
|
<TableHead>前缀</TableHead>
|
||||||
|
<TableHead>权限</TableHead>
|
||||||
|
<TableHead>最后使用</TableHead>
|
||||||
|
<TableHead>过期时间</TableHead>
|
||||||
|
<TableHead>创建时间</TableHead>
|
||||||
|
<TableHead className="text-right">操作</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{tokens.map((t) => (
|
||||||
|
<TableRow key={t.id}>
|
||||||
|
<TableCell className="font-medium">{t.name}</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{t.token_prefix}...
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
{t.permissions.map((p) => (
|
||||||
|
<Badge key={p} variant="outline" className="text-xs">
|
||||||
|
{p}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{t.last_used_at ? formatDate(t.last_used_at) : '未使用'}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{t.expires_at ? formatDate(t.expires_at) : '永不过期'}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{formatDate(t.created_at)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => setRevokeTarget(t)} title="撤销">
|
||||||
|
<Trash2 className="h-4 w-4 text-destructive" />
|
||||||
|
</Button>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between text-sm">
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
第 {page} 页 / 共 {totalPages} 页 ({total} 条)
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage(page - 1)}>
|
||||||
|
<ChevronLeft className="h-4 w-4 mr-1" />
|
||||||
|
上一页
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => setPage(page + 1)}>
|
||||||
|
下一页
|
||||||
|
<ChevronRight className="h-4 w-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 创建 Dialog */}
|
||||||
|
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>新建 API 密钥</DialogTitle>
|
||||||
|
<DialogDescription>创建新的 API 密钥用于接口调用</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>名称 *</Label>
|
||||||
|
<Input
|
||||||
|
value={createForm.name}
|
||||||
|
onChange={(e) => setCreateForm({ ...createForm, name: e.target.value })}
|
||||||
|
placeholder="例如: 生产环境"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>过期天数 (留空则永不过期)</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
value={createForm.expires_days}
|
||||||
|
onChange={(e) => setCreateForm({ ...createForm, expires_days: e.target.value })}
|
||||||
|
placeholder="365"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>权限 *</Label>
|
||||||
|
<div className="flex flex-wrap gap-3 mt-1">
|
||||||
|
{allPermissions.map((perm) => (
|
||||||
|
<label
|
||||||
|
key={perm.key}
|
||||||
|
className="flex items-center gap-2 cursor-pointer"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={createForm.permissions.includes(perm.key)}
|
||||||
|
onChange={() => togglePermission(perm.key)}
|
||||||
|
className="h-4 w-4 rounded border-input bg-transparent accent-primary cursor-pointer"
|
||||||
|
/>
|
||||||
|
<span className="text-sm text-foreground">{perm.label}</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setCreateOpen(false)}>取消</Button>
|
||||||
|
<Button onClick={handleCreate} disabled={creating || !createForm.name.trim() || createForm.permissions.length === 0}>
|
||||||
|
{creating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
创建
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* 创建成功 Dialog */}
|
||||||
|
<Dialog open={!!createdToken} onOpenChange={() => setCreatedToken(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2">
|
||||||
|
<AlertTriangle className="h-5 w-5 text-yellow-400" />
|
||||||
|
密钥已创建
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
请立即复制并安全保存此密钥,关闭后将无法再次查看完整密钥。
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="rounded-md bg-muted p-4">
|
||||||
|
<p className="text-xs text-muted-foreground mb-2">完整密钥</p>
|
||||||
|
<p className="font-mono text-sm break-all text-foreground">
|
||||||
|
{createdToken?.token}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-md bg-yellow-500/10 border border-yellow-500/20 p-3 text-sm text-yellow-400">
|
||||||
|
此密钥仅显示一次。请确保已保存到安全的位置。
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button onClick={copyToken} variant="outline">
|
||||||
|
{copied ? <Check className="h-4 w-4 mr-2" /> : <Copy className="h-4 w-4 mr-2" />}
|
||||||
|
{copied ? '已复制' : '复制密钥'}
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => setCreatedToken(null)}>我已保存</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* 撤销确认 */}
|
||||||
|
<Dialog open={!!revokeTarget} onOpenChange={() => setRevokeTarget(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>确认撤销</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
确定要撤销密钥 "{revokeTarget?.name}" 吗?使用此密钥的应用将立即失去访问权限。
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setRevokeTarget(null)}>取消</Button>
|
||||||
|
<Button variant="destructive" onClick={handleRevoke} disabled={revoking}>
|
||||||
|
{revoking && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
撤销
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
260
admin/src/app/(dashboard)/config/page.tsx
Normal file
260
admin/src/app/(dashboard)/config/page.tsx
Normal file
@@ -0,0 +1,260 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import useSWR from 'swr'
|
||||||
|
import {
|
||||||
|
Loader2,
|
||||||
|
Pencil,
|
||||||
|
RotateCcw,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogFooter,
|
||||||
|
DialogDescription,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { TableSkeleton } from '@/components/ui/skeleton'
|
||||||
|
import { ErrorBanner, EmptyState } from '@/components/ui/state'
|
||||||
|
import { ApiRequestError } from '@/lib/api-client'
|
||||||
|
import type { ConfigItem } from '@/lib/types'
|
||||||
|
|
||||||
|
const sourceLabels: Record<string, string> = {
|
||||||
|
default: '默认值',
|
||||||
|
env: '环境变量',
|
||||||
|
db: '数据库',
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceVariants: Record<string, 'secondary' | 'info' | 'default'> = {
|
||||||
|
default: 'secondary',
|
||||||
|
env: 'info',
|
||||||
|
db: 'default',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ConfigPage() {
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [activeTab, setActiveTab] = useState('all')
|
||||||
|
|
||||||
|
// SWR for config list
|
||||||
|
const { data: configs = [], isLoading, mutate } = useSWR(
|
||||||
|
['config', activeTab],
|
||||||
|
() => {
|
||||||
|
const params: Record<string, unknown> = {}
|
||||||
|
if (activeTab !== 'all') params.category = activeTab
|
||||||
|
return api.config.list(params)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// 编辑 Dialog
|
||||||
|
const [editTarget, setEditTarget] = useState<ConfigItem | null>(null)
|
||||||
|
const [editValue, setEditValue] = useState('')
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
|
||||||
|
function openEditDialog(config: ConfigItem) {
|
||||||
|
setEditTarget(config)
|
||||||
|
setEditValue(config.current_value ?? '')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSave() {
|
||||||
|
if (!editTarget) return
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
let parsedValue: string | number | boolean = editValue
|
||||||
|
if (editTarget.value_type === 'number') {
|
||||||
|
parsedValue = parseFloat(editValue) || 0
|
||||||
|
} else if (editTarget.value_type === 'boolean') {
|
||||||
|
parsedValue = editValue === 'true'
|
||||||
|
}
|
||||||
|
await api.config.update(editTarget.id, { value: parsedValue })
|
||||||
|
setEditTarget(null)
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) setError(err.body.message)
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatValue(value: unknown): string {
|
||||||
|
if (value === undefined || value === null) return '-'
|
||||||
|
if (typeof value === 'boolean') return value ? 'true' : 'false'
|
||||||
|
return String(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
const categoryLabels: Record<string, string> = {
|
||||||
|
all: '全部',
|
||||||
|
server: '服务器',
|
||||||
|
agent: 'Agent',
|
||||||
|
memory: '记忆',
|
||||||
|
llm: 'LLM',
|
||||||
|
security: '安全策略',
|
||||||
|
}
|
||||||
|
const categories = Object.keys(categoryLabels)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* 分类 Tabs */}
|
||||||
|
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||||
|
<TabsList>
|
||||||
|
{categories.map((cat) => (
|
||||||
|
<TabsTrigger key={cat} value={cat}>
|
||||||
|
{categoryLabels[cat] || cat}
|
||||||
|
</TabsTrigger>
|
||||||
|
))}
|
||||||
|
</TabsList>
|
||||||
|
</Tabs>
|
||||||
|
|
||||||
|
{error && <ErrorBanner message={error} onDismiss={() => setError('')} />}
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<TableSkeleton rows={8} cols={8} hasToolbar={false} />
|
||||||
|
) : error ? null : configs.length === 0 ? (
|
||||||
|
<EmptyState message="暂无配置项" />
|
||||||
|
) : (
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>分类</TableHead>
|
||||||
|
<TableHead>Key</TableHead>
|
||||||
|
<TableHead>当前值</TableHead>
|
||||||
|
<TableHead>默认值</TableHead>
|
||||||
|
<TableHead>来源</TableHead>
|
||||||
|
<TableHead>需重启</TableHead>
|
||||||
|
<TableHead>描述</TableHead>
|
||||||
|
<TableHead className="text-right">操作</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{configs.map((config) => (
|
||||||
|
<TableRow key={config.id}>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant="outline">{config.category}</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-sm">{config.key_path}</TableCell>
|
||||||
|
<TableCell className="font-mono text-sm max-w-[200px] truncate">
|
||||||
|
{formatValue(config.current_value)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground max-w-[200px] truncate">
|
||||||
|
{formatValue(config.default_value)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={sourceVariants[config.source] || 'secondary'}>
|
||||||
|
{sourceLabels[config.source] || config.source}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{config.requires_restart ? (
|
||||||
|
<Badge variant="warning">是</Badge>
|
||||||
|
) : (
|
||||||
|
<span className="text-muted-foreground">否</span>
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground max-w-[250px] truncate">
|
||||||
|
{config.description || '-'}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => openEditDialog(config)} title="编辑">
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 编辑 Dialog */}
|
||||||
|
<Dialog open={!!editTarget} onOpenChange={() => setEditTarget(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>编辑配置</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
修改 {editTarget?.key_path} 的值
|
||||||
|
{editTarget?.requires_restart && (
|
||||||
|
<span className="block mt-1 text-yellow-400 text-xs">
|
||||||
|
注意: 修改此配置需要重启服务才能生效
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Key</Label>
|
||||||
|
<Input value={editTarget?.key_path || ''} disabled />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>类型</Label>
|
||||||
|
<Input value={editTarget?.value_type || ''} disabled />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>
|
||||||
|
新值 {editTarget?.default_value != null && (
|
||||||
|
<span className="text-xs text-muted-foreground ml-2">
|
||||||
|
(默认: {formatValue(editTarget.default_value)})
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Label>
|
||||||
|
{editTarget?.value_type === 'boolean' ? (
|
||||||
|
<Select value={editValue} onValueChange={setEditValue}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="true">true</SelectItem>
|
||||||
|
<SelectItem value="false">false</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
) : (
|
||||||
|
<Input
|
||||||
|
type={editTarget?.value_type === 'number' ? 'number' : 'text'}
|
||||||
|
value={editValue}
|
||||||
|
onChange={(e) => setEditValue(e.target.value)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
if (editTarget?.default_value != null) {
|
||||||
|
setEditValue(String(editTarget.default_value))
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<RotateCcw className="h-4 w-4 mr-2" />
|
||||||
|
恢复默认
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" onClick={() => setEditTarget(null)}>取消</Button>
|
||||||
|
<Button onClick={handleSave} disabled={saving}>
|
||||||
|
{saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
保存
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
241
admin/src/app/(dashboard)/layout.tsx
Normal file
241
admin/src/app/(dashboard)/layout.tsx
Normal file
@@ -0,0 +1,241 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState, type ReactNode } from 'react'
|
||||||
|
import Link from 'next/link'
|
||||||
|
import { usePathname, useRouter } from 'next/navigation'
|
||||||
|
import {
|
||||||
|
LayoutDashboard,
|
||||||
|
Users,
|
||||||
|
Server,
|
||||||
|
Cpu,
|
||||||
|
Key,
|
||||||
|
BarChart3,
|
||||||
|
ArrowLeftRight,
|
||||||
|
Settings,
|
||||||
|
FileText,
|
||||||
|
MessageSquare,
|
||||||
|
Bot,
|
||||||
|
LogOut,
|
||||||
|
ChevronLeft,
|
||||||
|
Menu,
|
||||||
|
Bell,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import { AuthGuard, useAuth } from '@/components/auth-guard'
|
||||||
|
import { logout } from '@/lib/auth'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
/** 权限常量 — 与后端 db.rs SEED_ROLES 保持同步 */
|
||||||
|
const ROLE_PERMISSIONS: Record<string, string[]> = {
|
||||||
|
super_admin: ['admin:full', 'account:admin', 'provider:manage', 'model:manage', 'relay:admin', 'config:write', 'prompt:read', 'prompt:write', 'prompt:publish', 'prompt:admin'],
|
||||||
|
admin: ['account:read', 'account:admin', 'provider:manage', 'model:read', 'model:manage', 'relay:use', 'relay:admin', 'config:read', 'config:write', 'prompt:read', 'prompt:write', 'prompt:publish'],
|
||||||
|
user: ['model:read', 'relay:use', 'config:read', 'prompt:read'],
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 根据 role 获取权限列表 */
|
||||||
|
function getPermissionsForRole(role: string): string[] {
|
||||||
|
return ROLE_PERMISSIONS[role] ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
const navItems = [
|
||||||
|
{ href: '/', label: '仪表盘', icon: LayoutDashboard },
|
||||||
|
{ href: '/accounts', label: '账号管理', icon: Users, permission: 'account:admin' },
|
||||||
|
{ href: '/providers', label: '服务商', icon: Server, permission: 'provider:manage' },
|
||||||
|
{ href: '/models', label: '模型管理', icon: Cpu, permission: 'model:read' },
|
||||||
|
{ href: '/agent-templates', label: 'Agent 模板', icon: Bot, permission: 'model:read' },
|
||||||
|
{ href: '/api-keys', label: 'API 密钥', icon: Key, permission: 'admin:full' },
|
||||||
|
{ href: '/usage', label: '用量统计', icon: BarChart3, permission: 'admin:full' },
|
||||||
|
{ href: '/relay', label: '中转任务', icon: ArrowLeftRight, permission: 'relay:use' },
|
||||||
|
{ href: '/config', label: '系统配置', icon: Settings, permission: 'config:read' },
|
||||||
|
{ href: '/prompts', label: '提示词管理', icon: MessageSquare, permission: 'prompt:read' },
|
||||||
|
{ href: '/logs', label: '操作日志', icon: FileText, permission: 'admin:full' },
|
||||||
|
]
|
||||||
|
|
||||||
|
function Sidebar({
|
||||||
|
collapsed,
|
||||||
|
onToggle,
|
||||||
|
}: {
|
||||||
|
collapsed: boolean
|
||||||
|
onToggle: () => void
|
||||||
|
}) {
|
||||||
|
const pathname = usePathname()
|
||||||
|
const router = useRouter()
|
||||||
|
const { account } = useAuth()
|
||||||
|
|
||||||
|
const permissions = account ? getPermissionsForRole(account.role) : []
|
||||||
|
|
||||||
|
function handleLogout() {
|
||||||
|
logout()
|
||||||
|
router.replace('/login')
|
||||||
|
}
|
||||||
|
|
||||||
|
const filteredNavItems = navItems.filter((item) => {
|
||||||
|
if (!item.permission) return true
|
||||||
|
return permissions.includes(item.permission) || permissions.includes('admin:full')
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside
|
||||||
|
className={cn(
|
||||||
|
'fixed left-0 top-0 z-40 flex h-screen flex-col border-r border-border bg-card transition-all duration-300',
|
||||||
|
collapsed ? 'w-16' : 'w-64',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{/* Logo */}
|
||||||
|
<div className="flex h-14 items-center border-b border-border px-4">
|
||||||
|
<Link href="/" className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<div className="flex h-8 w-8 items-center justify-center rounded-md bg-primary text-primary-foreground font-bold text-sm">
|
||||||
|
Z
|
||||||
|
</div>
|
||||||
|
{!collapsed && (
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<span className="text-sm font-bold text-foreground">ZCLAW</span>
|
||||||
|
<span className="text-[10px] text-muted-foreground">Admin</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 导航 */}
|
||||||
|
<nav className="flex-1 overflow-y-auto scrollbar-thin py-2 px-2">
|
||||||
|
<ul className="space-y-1">
|
||||||
|
{filteredNavItems.map((item) => {
|
||||||
|
const isActive =
|
||||||
|
item.href === '/'
|
||||||
|
? pathname === '/'
|
||||||
|
: pathname.startsWith(item.href)
|
||||||
|
const Icon = item.icon
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li key={item.href}>
|
||||||
|
<Link
|
||||||
|
href={item.href}
|
||||||
|
className={cn(
|
||||||
|
'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors duration-200 cursor-pointer',
|
||||||
|
isActive
|
||||||
|
? 'bg-muted text-green-400'
|
||||||
|
: 'text-muted-foreground hover:bg-muted hover:text-foreground',
|
||||||
|
collapsed && 'justify-center px-2',
|
||||||
|
)}
|
||||||
|
title={collapsed ? item.label : undefined}
|
||||||
|
>
|
||||||
|
<Icon className="h-4 w-4 shrink-0" />
|
||||||
|
{!collapsed && <span>{item.label}</span>}
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{/* 底部折叠按钮 */}
|
||||||
|
<div className="border-t border-border p-2">
|
||||||
|
<button
|
||||||
|
onClick={onToggle}
|
||||||
|
className="flex w-full items-center justify-center rounded-md px-3 py-2 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors duration-200 cursor-pointer"
|
||||||
|
>
|
||||||
|
<ChevronLeft
|
||||||
|
className={cn(
|
||||||
|
'h-4 w-4 transition-transform duration-200',
|
||||||
|
collapsed && 'rotate-180',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 用户信息 */}
|
||||||
|
{!collapsed && (
|
||||||
|
<div className="border-t border-border p-3">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-medium text-foreground">
|
||||||
|
{account?.display_name?.[0] || account?.username?.[0] || 'A'}
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="truncate text-sm font-medium text-foreground">
|
||||||
|
{account?.display_name || account?.username || 'Admin'}
|
||||||
|
</p>
|
||||||
|
<p className="truncate text-xs text-muted-foreground">
|
||||||
|
{account?.role || 'admin'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleLogout}
|
||||||
|
className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-destructive transition-colors duration-200 cursor-pointer"
|
||||||
|
title="退出登录"
|
||||||
|
>
|
||||||
|
<LogOut className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</aside>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Header() {
|
||||||
|
const pathname = usePathname()
|
||||||
|
const currentNav = navItems.find(
|
||||||
|
(item) =>
|
||||||
|
item.href === '/'
|
||||||
|
? pathname === '/'
|
||||||
|
: pathname.startsWith(item.href),
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<header className="sticky top-0 z-30 flex h-14 items-center border-b border-border bg-background/80 backdrop-blur-sm px-6">
|
||||||
|
{/* 移动端菜单按钮 */}
|
||||||
|
<MobileMenuButton />
|
||||||
|
|
||||||
|
{/* 页面标题 */}
|
||||||
|
<h1 className="text-lg font-semibold text-foreground">
|
||||||
|
{currentNav?.label || '仪表盘'}
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<div className="ml-auto flex items-center gap-2">
|
||||||
|
{/* 通知 */}
|
||||||
|
<button
|
||||||
|
className="relative rounded-md p-2 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors duration-200 cursor-pointer"
|
||||||
|
title="通知"
|
||||||
|
>
|
||||||
|
<Bell className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MobileMenuButton() {
|
||||||
|
// Placeholder for mobile menu toggle
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
className="mr-3 rounded-md p-2 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors duration-200 lg:hidden cursor-pointer"
|
||||||
|
>
|
||||||
|
<Menu className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DashboardLayout({ children }: { children: ReactNode }) {
|
||||||
|
const [sidebarCollapsed, setSidebarCollapsed] = useState(false)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthGuard>
|
||||||
|
<div className="flex min-h-screen">
|
||||||
|
<Sidebar
|
||||||
|
collapsed={sidebarCollapsed}
|
||||||
|
onToggle={() => setSidebarCollapsed(!sidebarCollapsed)}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'flex flex-1 flex-col transition-all duration-300',
|
||||||
|
sidebarCollapsed ? 'ml-16' : 'ml-64',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Header />
|
||||||
|
<main className="flex-1 overflow-auto p-6 scrollbar-thin">
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</AuthGuard>
|
||||||
|
)
|
||||||
|
}
|
||||||
414
admin/src/app/(dashboard)/models/page.tsx
Normal file
414
admin/src/app/(dashboard)/models/page.tsx
Normal file
@@ -0,0 +1,414 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import useSWR from 'swr'
|
||||||
|
import {
|
||||||
|
Plus,
|
||||||
|
Loader2,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
Pencil,
|
||||||
|
Trash2,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogFooter,
|
||||||
|
DialogDescription,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import { TableSkeleton } from '@/components/ui/skeleton'
|
||||||
|
import { ErrorBanner, EmptyState } from '@/components/ui/state'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { ApiRequestError } from '@/lib/api-client'
|
||||||
|
import { formatNumber } from '@/lib/utils'
|
||||||
|
import type { Model, Provider } from '@/lib/types'
|
||||||
|
|
||||||
|
const PAGE_SIZE = 20
|
||||||
|
|
||||||
|
interface ModelForm {
|
||||||
|
provider_id: string
|
||||||
|
model_id: string
|
||||||
|
alias: string
|
||||||
|
context_window: string
|
||||||
|
max_output_tokens: string
|
||||||
|
supports_streaming: boolean
|
||||||
|
supports_vision: boolean
|
||||||
|
enabled: boolean
|
||||||
|
pricing_input: string
|
||||||
|
pricing_output: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const emptyForm: ModelForm = {
|
||||||
|
provider_id: '',
|
||||||
|
model_id: '',
|
||||||
|
alias: '',
|
||||||
|
context_window: '4096',
|
||||||
|
max_output_tokens: '4096',
|
||||||
|
supports_streaming: true,
|
||||||
|
supports_vision: false,
|
||||||
|
enabled: true,
|
||||||
|
pricing_input: '',
|
||||||
|
pricing_output: '',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ModelsPage() {
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [providerFilter, setProviderFilter] = useState<string>('all')
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
// SWR for models list
|
||||||
|
const { data, isLoading, mutate } = useSWR(
|
||||||
|
['models', page, providerFilter],
|
||||||
|
() => {
|
||||||
|
const params: Record<string, unknown> = { page, page_size: PAGE_SIZE }
|
||||||
|
if (providerFilter !== 'all') params.provider_id = providerFilter
|
||||||
|
return api.models.list(params)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
const models = data?.items ?? []
|
||||||
|
const total = data?.total ?? 0
|
||||||
|
|
||||||
|
// SWR for providers list (dropdown)
|
||||||
|
const { data: providersData } = useSWR(
|
||||||
|
['providers.all'],
|
||||||
|
() => api.providers.list({ page: 1, page_size: 100 })
|
||||||
|
)
|
||||||
|
const providers = providersData?.items ?? []
|
||||||
|
|
||||||
|
// Dialog
|
||||||
|
const [dialogOpen, setDialogOpen] = useState(false)
|
||||||
|
const [editTarget, setEditTarget] = useState<Model | null>(null)
|
||||||
|
const [form, setForm] = useState<ModelForm>(emptyForm)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
|
||||||
|
// 删除
|
||||||
|
const [deleteTarget, setDeleteTarget] = useState<Model | null>(null)
|
||||||
|
const [deleting, setDeleting] = useState(false)
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
|
||||||
|
|
||||||
|
const providerMap = new Map(providers.map((p) => [p.id, p.display_name || p.name]))
|
||||||
|
|
||||||
|
function openCreateDialog() {
|
||||||
|
setEditTarget(null)
|
||||||
|
setForm(emptyForm)
|
||||||
|
setDialogOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEditDialog(model: Model) {
|
||||||
|
setEditTarget(model)
|
||||||
|
setForm({
|
||||||
|
provider_id: model.provider_id,
|
||||||
|
model_id: model.model_id,
|
||||||
|
alias: model.alias,
|
||||||
|
context_window: model.context_window.toString(),
|
||||||
|
max_output_tokens: model.max_output_tokens.toString(),
|
||||||
|
supports_streaming: model.supports_streaming,
|
||||||
|
supports_vision: model.supports_vision,
|
||||||
|
enabled: model.enabled,
|
||||||
|
pricing_input: model.pricing_input.toString(),
|
||||||
|
pricing_output: model.pricing_output.toString(),
|
||||||
|
})
|
||||||
|
setDialogOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSave() {
|
||||||
|
if (!form.model_id.trim() || !form.provider_id) return
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
provider_id: form.provider_id,
|
||||||
|
model_id: form.model_id.trim(),
|
||||||
|
alias: form.alias.trim(),
|
||||||
|
context_window: parseInt(form.context_window, 10) || 4096,
|
||||||
|
max_output_tokens: parseInt(form.max_output_tokens, 10) || 4096,
|
||||||
|
supports_streaming: form.supports_streaming,
|
||||||
|
supports_vision: form.supports_vision,
|
||||||
|
enabled: form.enabled,
|
||||||
|
pricing_input: parseFloat(form.pricing_input) || 0,
|
||||||
|
pricing_output: parseFloat(form.pricing_output) || 0,
|
||||||
|
}
|
||||||
|
if (editTarget) {
|
||||||
|
await api.models.update(editTarget.id, payload)
|
||||||
|
} else {
|
||||||
|
await api.models.create(payload)
|
||||||
|
}
|
||||||
|
setDialogOpen(false)
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) setError(err.body.message)
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete() {
|
||||||
|
if (!deleteTarget) return
|
||||||
|
setDeleting(true)
|
||||||
|
try {
|
||||||
|
await api.models.delete(deleteTarget.id)
|
||||||
|
setDeleteTarget(null)
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) setError(err.body.message)
|
||||||
|
} finally {
|
||||||
|
setDeleting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Select value={providerFilter} onValueChange={(v) => { setProviderFilter(v); setPage(1) }}>
|
||||||
|
<SelectTrigger className="w-[200px]">
|
||||||
|
<SelectValue placeholder="按服务商筛选" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">全部服务商</SelectItem>
|
||||||
|
{providers.map((p) => (
|
||||||
|
<SelectItem key={p.id} value={p.id}>
|
||||||
|
{p.display_name || p.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<Button onClick={openCreateDialog}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
新建模型
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <ErrorBanner message={error} onDismiss={() => setError('')} />}
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<TableSkeleton rows={8} cols={9} hasToolbar={false} />
|
||||||
|
) : error ? null : models.length === 0 ? (
|
||||||
|
<EmptyState />
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>模型 ID</TableHead>
|
||||||
|
<TableHead>别名</TableHead>
|
||||||
|
<TableHead>服务商</TableHead>
|
||||||
|
<TableHead>上下文窗口</TableHead>
|
||||||
|
<TableHead>最大输出</TableHead>
|
||||||
|
<TableHead>流式</TableHead>
|
||||||
|
<TableHead>视觉</TableHead>
|
||||||
|
<TableHead>启用</TableHead>
|
||||||
|
<TableHead className="text-right">操作</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{models.map((m) => (
|
||||||
|
<TableRow key={m.id}>
|
||||||
|
<TableCell className="font-mono text-sm">{m.model_id}</TableCell>
|
||||||
|
<TableCell>{m.alias || '-'}</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">
|
||||||
|
{providerMap.get(m.provider_id) || m.provider_id.slice(0, 8)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{formatNumber(m.context_window)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{formatNumber(m.max_output_tokens)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={m.supports_streaming ? 'success' : 'secondary'}>
|
||||||
|
{m.supports_streaming ? '是' : '否'}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={m.supports_vision ? 'success' : 'secondary'}>
|
||||||
|
{m.supports_vision ? '是' : '否'}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={m.enabled ? 'success' : 'destructive'}>
|
||||||
|
{m.enabled ? '启用' : '禁用'}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<div className="flex items-center justify-end gap-1">
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => openEditDialog(m)} title="编辑">
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => setDeleteTarget(m)} title="删除">
|
||||||
|
<Trash2 className="h-4 w-4 text-destructive" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between text-sm">
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
第 {page} 页 / 共 {totalPages} 页 ({total} 条)
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage(page - 1)}>
|
||||||
|
<ChevronLeft className="h-4 w-4 mr-1" />
|
||||||
|
上一页
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => setPage(page + 1)}>
|
||||||
|
下一页
|
||||||
|
<ChevronRight className="h-4 w-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 创建/编辑 Dialog */}
|
||||||
|
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||||
|
<DialogContent className="max-w-lg">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{editTarget ? '编辑模型' : '新建模型'}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{editTarget ? '修改模型配置' : '添加新的 AI 模型'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-4 max-h-[60vh] overflow-y-auto scrollbar-thin pr-1">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>服务商 *</Label>
|
||||||
|
<Select value={form.provider_id} onValueChange={(v) => setForm({ ...form, provider_id: v })} disabled={!!editTarget}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="选择服务商" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{providers.map((p) => (
|
||||||
|
<SelectItem key={p.id} value={p.id}>
|
||||||
|
{p.display_name || p.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>模型 ID *</Label>
|
||||||
|
<Input
|
||||||
|
value={form.model_id}
|
||||||
|
onChange={(e) => setForm({ ...form, model_id: e.target.value })}
|
||||||
|
placeholder="gpt-4o"
|
||||||
|
disabled={!!editTarget}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>别名</Label>
|
||||||
|
<Input
|
||||||
|
value={form.alias}
|
||||||
|
onChange={(e) => setForm({ ...form, alias: e.target.value })}
|
||||||
|
placeholder="GPT-4o"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>上下文窗口</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
value={form.context_window}
|
||||||
|
onChange={(e) => setForm({ ...form, context_window: e.target.value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>最大输出 Tokens</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
value={form.max_output_tokens}
|
||||||
|
onChange={(e) => setForm({ ...form, max_output_tokens: e.target.value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Input 定价 ($/1M tokens)</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
value={form.pricing_input}
|
||||||
|
onChange={(e) => setForm({ ...form, pricing_input: e.target.value })}
|
||||||
|
placeholder="0"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Output 定价 ($/1M tokens)</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
value={form.pricing_output}
|
||||||
|
onChange={(e) => setForm({ ...form, pricing_output: e.target.value })}
|
||||||
|
placeholder="0"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-6">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Switch checked={form.supports_streaming} onCheckedChange={(v) => setForm({ ...form, supports_streaming: v })} />
|
||||||
|
<Label>流式</Label>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Switch checked={form.supports_vision} onCheckedChange={(v) => setForm({ ...form, supports_vision: v })} />
|
||||||
|
<Label>视觉</Label>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Switch checked={form.enabled} onCheckedChange={(v) => setForm({ ...form, enabled: v })} />
|
||||||
|
<Label>启用</Label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
|
||||||
|
<Button onClick={handleSave} disabled={saving || !form.model_id.trim() || !form.provider_id}>
|
||||||
|
{saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
保存
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* 删除确认 */}
|
||||||
|
<Dialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>确认删除</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
确定要删除模型 "{deleteTarget?.alias || deleteTarget?.model_id}" 吗?此操作不可撤销。
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setDeleteTarget(null)}>取消</Button>
|
||||||
|
<Button variant="destructive" onClick={handleDelete} disabled={deleting}>
|
||||||
|
{deleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
315
admin/src/app/(dashboard)/page.tsx
Normal file
315
admin/src/app/(dashboard)/page.tsx
Normal file
@@ -0,0 +1,315 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import {
|
||||||
|
Users,
|
||||||
|
Server,
|
||||||
|
ArrowLeftRight,
|
||||||
|
Zap,
|
||||||
|
TrendingUp,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import {
|
||||||
|
AreaChart,
|
||||||
|
Area,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
CartesianGrid,
|
||||||
|
Tooltip,
|
||||||
|
ResponsiveContainer,
|
||||||
|
BarChart,
|
||||||
|
Bar,
|
||||||
|
Legend,
|
||||||
|
} from 'recharts'
|
||||||
|
import useSWR from 'swr'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { StatsSkeleton } from '@/components/ui/skeleton'
|
||||||
|
import { ChartSkeleton } from '@/components/ui/skeleton'
|
||||||
|
import { TableSkeleton } from '@/components/ui/skeleton'
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { formatNumber, formatDate } from '@/lib/utils'
|
||||||
|
import type {
|
||||||
|
DashboardStats,
|
||||||
|
UsageRecord,
|
||||||
|
OperationLog,
|
||||||
|
} from '@/lib/types'
|
||||||
|
|
||||||
|
interface StatCardProps {
|
||||||
|
title: string
|
||||||
|
value: string | number
|
||||||
|
icon: React.ReactNode
|
||||||
|
color: string
|
||||||
|
subtitle?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function StatCard({ title, value, icon, color, subtitle }: StatCardProps) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="p-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-muted-foreground">{title}</p>
|
||||||
|
<p className="mt-1 text-2xl font-bold text-foreground">{value}</p>
|
||||||
|
{subtitle && (
|
||||||
|
<p className="mt-1 text-xs text-muted-foreground">{subtitle}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={`flex h-10 w-10 items-center justify-center rounded-lg ${color}`}
|
||||||
|
>
|
||||||
|
{icon}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function StatusBadge({ status }: { status: string }) {
|
||||||
|
const variantMap: Record<string, 'success' | 'destructive' | 'warning' | 'info' | 'secondary'> = {
|
||||||
|
active: 'success',
|
||||||
|
completed: 'success',
|
||||||
|
disabled: 'destructive',
|
||||||
|
failed: 'destructive',
|
||||||
|
processing: 'info',
|
||||||
|
queued: 'warning',
|
||||||
|
suspended: 'destructive',
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Badge variant={variantMap[status] || 'secondary'}>{status}</Badge>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DashboardPage() {
|
||||||
|
const { data: stats, isLoading: statsLoading } = useSWR(
|
||||||
|
['stats.dashboard'],
|
||||||
|
() => api.stats.dashboard(),
|
||||||
|
)
|
||||||
|
|
||||||
|
const { data: usageData = [], isLoading: usageLoading } = useSWR(
|
||||||
|
['usage.daily.30'],
|
||||||
|
() => api.usage.daily({ days: 30 }),
|
||||||
|
)
|
||||||
|
|
||||||
|
const { data: logsData, isLoading: logsLoading } = useSWR(
|
||||||
|
['logs.recent'],
|
||||||
|
() => api.logs.list({ page: 1, page_size: 5 }),
|
||||||
|
)
|
||||||
|
|
||||||
|
const recentLogs: OperationLog[] = logsData?.items ?? []
|
||||||
|
|
||||||
|
const chartData = usageData.map((r: UsageRecord) => ({
|
||||||
|
day: r.day.slice(5), // MM-DD
|
||||||
|
请求量: r.count,
|
||||||
|
Input: r.input_tokens,
|
||||||
|
Output: r.output_tokens,
|
||||||
|
}))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* 统计卡片 */}
|
||||||
|
{statsLoading ? (
|
||||||
|
<StatsSkeleton count={4} />
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<StatCard
|
||||||
|
title="总账号数"
|
||||||
|
value={stats?.total_accounts ?? '-'}
|
||||||
|
icon={<Users className="h-5 w-5 text-blue-400" />}
|
||||||
|
color="bg-blue-500/10"
|
||||||
|
subtitle={`活跃 ${stats?.active_accounts ?? 0}`}
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
title="活跃服务商"
|
||||||
|
value={stats?.active_providers ?? '-'}
|
||||||
|
icon={<Server className="h-5 w-5 text-green-400" />}
|
||||||
|
color="bg-green-500/10"
|
||||||
|
subtitle={`模型 ${stats?.active_models ?? 0}`}
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
title="今日请求"
|
||||||
|
value={stats?.tasks_today ?? '-'}
|
||||||
|
icon={<ArrowLeftRight className="h-5 w-5 text-purple-400" />}
|
||||||
|
color="bg-purple-500/10"
|
||||||
|
subtitle="中转任务"
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
title="今日 Token"
|
||||||
|
value={formatNumber((stats?.tokens_today_input ?? 0) + (stats?.tokens_today_output ?? 0))}
|
||||||
|
icon={<Zap className="h-5 w-5 text-orange-400" />}
|
||||||
|
color="bg-orange-500/10"
|
||||||
|
subtitle={`In: ${formatNumber(stats?.tokens_today_input ?? 0)} / Out: ${formatNumber(stats?.tokens_today_output ?? 0)}`}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 图表 */}
|
||||||
|
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
|
||||||
|
{/* 请求趋势 */}
|
||||||
|
{usageLoading ? (
|
||||||
|
<ChartSkeleton height={280} />
|
||||||
|
) : (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2 text-base">
|
||||||
|
<TrendingUp className="h-4 w-4 text-primary" />
|
||||||
|
请求趋势 (30 天)
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{chartData.length > 0 ? (
|
||||||
|
<ResponsiveContainer width="100%" height={280}>
|
||||||
|
<AreaChart data={chartData}>
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="colorRequests" x1="0" y1="0" x2="0" y2="1">
|
||||||
|
<stop offset="5%" stopColor="#22C55E" stopOpacity={0.3} />
|
||||||
|
<stop offset="95%" stopColor="#22C55E" stopOpacity={0} />
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#1E293B" />
|
||||||
|
<XAxis
|
||||||
|
dataKey="day"
|
||||||
|
tick={{ fontSize: 12, fill: '#94A3B8' }}
|
||||||
|
axisLine={{ stroke: '#1E293B' }}
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
tick={{ fontSize: 12, fill: '#94A3B8' }}
|
||||||
|
axisLine={{ stroke: '#1E293B' }}
|
||||||
|
/>
|
||||||
|
<Tooltip
|
||||||
|
contentStyle={{
|
||||||
|
backgroundColor: '#0F172A',
|
||||||
|
border: '1px solid #1E293B',
|
||||||
|
borderRadius: '8px',
|
||||||
|
color: '#F8FAFC',
|
||||||
|
fontSize: '12px',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Area
|
||||||
|
type="monotone"
|
||||||
|
dataKey="请求量"
|
||||||
|
stroke="#22C55E"
|
||||||
|
fillOpacity={1}
|
||||||
|
fill="url(#colorRequests)"
|
||||||
|
strokeWidth={2}
|
||||||
|
/>
|
||||||
|
</AreaChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
) : (
|
||||||
|
<div className="flex h-[280px] items-center justify-center text-muted-foreground text-sm">
|
||||||
|
暂无数据
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Token 用量 */}
|
||||||
|
{usageLoading ? (
|
||||||
|
<ChartSkeleton height={280} />
|
||||||
|
) : (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2 text-base">
|
||||||
|
<Zap className="h-4 w-4 text-orange-400" />
|
||||||
|
Token 用量 (30 天)
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{chartData.length > 0 ? (
|
||||||
|
<ResponsiveContainer width="100%" height={280}>
|
||||||
|
<BarChart data={chartData}>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#1E293B" />
|
||||||
|
<XAxis
|
||||||
|
dataKey="day"
|
||||||
|
tick={{ fontSize: 12, fill: '#94A3B8' }}
|
||||||
|
axisLine={{ stroke: '#1E293B' }}
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
tick={{ fontSize: 12, fill: '#94A3B8' }}
|
||||||
|
axisLine={{ stroke: '#1E293B' }}
|
||||||
|
/>
|
||||||
|
<Tooltip
|
||||||
|
contentStyle={{
|
||||||
|
backgroundColor: '#0F172A',
|
||||||
|
border: '1px solid #1E293B',
|
||||||
|
borderRadius: '8px',
|
||||||
|
color: '#F8FAFC',
|
||||||
|
fontSize: '12px',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Legend
|
||||||
|
wrapperStyle={{ fontSize: '12px', color: '#94A3B8' }}
|
||||||
|
/>
|
||||||
|
<Bar dataKey="Input" fill="#3B82F6" radius={[2, 2, 0, 0]} />
|
||||||
|
<Bar dataKey="Output" fill="#F97316" radius={[2, 2, 0, 0]} />
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
) : (
|
||||||
|
<div className="flex h-[280px] items-center justify-center text-muted-foreground text-sm">
|
||||||
|
暂无数据
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 最近操作日志 */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-base">最近操作</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{logsLoading ? (
|
||||||
|
<TableSkeleton rows={5} cols={5} hasToolbar={false} />
|
||||||
|
) : recentLogs.length > 0 ? (
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>时间</TableHead>
|
||||||
|
<TableHead>账号 ID</TableHead>
|
||||||
|
<TableHead>操作</TableHead>
|
||||||
|
<TableHead>目标类型</TableHead>
|
||||||
|
<TableHead>目标 ID</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{recentLogs.map((log) => (
|
||||||
|
<TableRow key={log.id}>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{formatDate(log.created_at)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs">
|
||||||
|
{log.account_id.slice(0, 8)}...
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant="outline">{log.action}</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">
|
||||||
|
{log.target_type}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{log.target_id.slice(0, 8)}...
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
) : (
|
||||||
|
<div className="flex h-32 items-center justify-center text-muted-foreground text-sm">
|
||||||
|
暂无操作日志
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
341
admin/src/app/(dashboard)/prompts/page.tsx
Normal file
341
admin/src/app/(dashboard)/prompts/page.tsx
Normal file
@@ -0,0 +1,341 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import useSWR from 'swr'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import type { PromptTemplate, PromptVersion } from '@/lib/types'
|
||||||
|
import { EmptyState } from '@/components/ui/state'
|
||||||
|
import { TableSkeleton } from '@/components/ui/skeleton'
|
||||||
|
|
||||||
|
export default function PromptsPage() {
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [selectedName, setSelectedName] = useState<string | null>(null)
|
||||||
|
const [versions, setVersions] = useState<PromptVersion[]>([])
|
||||||
|
const [showCreate, setShowCreate] = useState(false)
|
||||||
|
const [showNewVersion, setShowNewVersion] = useState(false)
|
||||||
|
const [filter, setFilter] = useState<{ source?: string; status?: string }>({})
|
||||||
|
|
||||||
|
const { data, error, isLoading, mutate } = useSWR(
|
||||||
|
['prompts.list', page, filter.source, filter.status],
|
||||||
|
() => api.prompts.list({ page, page_size: 50, ...filter }),
|
||||||
|
)
|
||||||
|
|
||||||
|
const templates = data?.items ?? []
|
||||||
|
const total = data?.total ?? 0
|
||||||
|
|
||||||
|
const fetchVersions = async (name: string) => {
|
||||||
|
try {
|
||||||
|
const res = await api.prompts.listVersions(name)
|
||||||
|
setVersions(res)
|
||||||
|
setSelectedName(name)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch versions:', err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCreate = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault()
|
||||||
|
const fd = new FormData(e.currentTarget)
|
||||||
|
try {
|
||||||
|
await api.prompts.create({
|
||||||
|
name: fd.get('name') as string,
|
||||||
|
category: fd.get('category') as string,
|
||||||
|
description: (fd.get('description') as string) || undefined,
|
||||||
|
source: 'custom',
|
||||||
|
system_prompt: fd.get('system_prompt') as string,
|
||||||
|
})
|
||||||
|
setShowCreate(false)
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to create prompt:', err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleNewVersion = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!selectedName) return
|
||||||
|
const fd = new FormData(e.currentTarget)
|
||||||
|
try {
|
||||||
|
await api.prompts.createVersion(selectedName, {
|
||||||
|
system_prompt: fd.get('system_prompt') as string,
|
||||||
|
changelog: (fd.get('changelog') as string) || undefined,
|
||||||
|
})
|
||||||
|
setShowNewVersion(false)
|
||||||
|
fetchVersions(selectedName)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to create version:', err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRollback = async (name: string, version: number) => {
|
||||||
|
if (!confirm(`确认回退到版本 ${version}?`)) return
|
||||||
|
try {
|
||||||
|
await api.prompts.rollback(name, version)
|
||||||
|
fetchVersions(name)
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to rollback:', err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleArchive = async (name: string) => {
|
||||||
|
if (!confirm(`确认归档 ${name}?`)) return
|
||||||
|
try {
|
||||||
|
await api.prompts.archive(name)
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to archive:', err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusBadge = (status: string) => {
|
||||||
|
const colors: Record<string, string> = {
|
||||||
|
active: 'bg-emerald-500/20 text-emerald-400',
|
||||||
|
deprecated: 'bg-amber-500/20 text-amber-400',
|
||||||
|
archived: 'bg-zinc-500/20 text-zinc-400',
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<span className={`px-2 py-0.5 text-xs rounded-full ${colors[status] || colors.archived}`}>
|
||||||
|
{status}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceBadge = (source: string) => {
|
||||||
|
const colors: Record<string, string> = {
|
||||||
|
builtin: 'bg-blue-500/20 text-blue-400',
|
||||||
|
custom: 'bg-purple-500/20 text-purple-400',
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<span className={`px-2 py-0.5 text-xs rounded-full ${colors[source] || ''}`}>
|
||||||
|
{source === 'builtin' ? '内置' : '自定义'}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-white">提示词管理</h1>
|
||||||
|
<p className="text-sm text-zinc-400 mt-1">管理内置和自定义提示词模板,支持版本控制和 OTA 分发</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreate(true)}
|
||||||
|
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm"
|
||||||
|
>
|
||||||
|
+ 新建模板
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filters */}
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{(['all', 'builtin', 'custom'] as const).map(s => (
|
||||||
|
<button
|
||||||
|
key={s}
|
||||||
|
onClick={() => setFilter(s === 'all' ? {} : { source: s })}
|
||||||
|
className={`px-3 py-1 text-sm rounded-lg transition-colors ${
|
||||||
|
(filter.source || 'all') === s
|
||||||
|
? 'bg-zinc-700 text-white'
|
||||||
|
: 'bg-zinc-800 text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{s === 'all' ? '全部' : s === 'builtin' ? '内置' : '自定义'}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Template List */}
|
||||||
|
<div className="bg-zinc-900 rounded-xl border border-zinc-800 overflow-hidden">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-zinc-800">
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">名称</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">分类</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">来源</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">版本</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">状态</th>
|
||||||
|
<th className="text-left px-4 py-3 text-zinc-400 font-medium">更新时间</th>
|
||||||
|
<th className="text-right px-4 py-3 text-zinc-400 font-medium">操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{isLoading ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={7}>
|
||||||
|
<TableSkeleton rows={5} cols={7} hasToolbar={false} />
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : error ? (
|
||||||
|
<tr><td colSpan={7} className="px-4 py-8 text-center text-red-400">加载失败</td></tr>
|
||||||
|
) : templates.length === 0 ? (
|
||||||
|
<tr><td colSpan={7}><EmptyState message="暂无提示词模板" /></td></tr>
|
||||||
|
) : (
|
||||||
|
templates.map(t => (
|
||||||
|
<tr key={t.id} className="border-b border-zinc-800/50 hover:bg-zinc-800/30">
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<button
|
||||||
|
onClick={() => fetchVersions(t.name)}
|
||||||
|
className="text-blue-400 hover:text-blue-300 font-mono"
|
||||||
|
>
|
||||||
|
{t.name}
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-zinc-400">{t.category}</td>
|
||||||
|
<td className="px-4 py-3">{sourceBadge(t.source)}</td>
|
||||||
|
<td className="px-4 py-3 text-zinc-300">v{t.current_version}</td>
|
||||||
|
<td className="px-4 py-3">{statusBadge(t.status)}</td>
|
||||||
|
<td className="px-4 py-3 text-zinc-500 text-xs">
|
||||||
|
{new Date(t.updated_at).toLocaleString('zh-CN')}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-right">
|
||||||
|
<button
|
||||||
|
onClick={() => fetchVersions(t.name)}
|
||||||
|
className="text-zinc-400 hover:text-white mr-2"
|
||||||
|
>
|
||||||
|
历史
|
||||||
|
</button>
|
||||||
|
{t.source === 'custom' && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleArchive(t.name)}
|
||||||
|
className="text-red-400 hover:text-red-300"
|
||||||
|
>
|
||||||
|
归档
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<div className="px-4 py-2 text-xs text-zinc-500 border-t border-zinc-800">
|
||||||
|
共 {total} 个模板
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Version History Panel */}
|
||||||
|
{selectedName && (
|
||||||
|
<div className="bg-zinc-900 rounded-xl border border-zinc-800 p-4">
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h2 className="text-lg font-semibold text-white">
|
||||||
|
{selectedName} — 版本历史
|
||||||
|
</h2>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => setShowNewVersion(true)}
|
||||||
|
className="px-3 py-1.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-xs"
|
||||||
|
>
|
||||||
|
发布新版本
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => { setSelectedName(null); setVersions([]) }}
|
||||||
|
className="px-3 py-1.5 bg-zinc-700 text-white rounded-lg hover:bg-zinc-600 text-xs"
|
||||||
|
>
|
||||||
|
关闭
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-3">
|
||||||
|
{versions.map(v => (
|
||||||
|
<div key={v.id} className="bg-zinc-800/50 rounded-lg p-3">
|
||||||
|
<div className="flex items-center justify-between mb-2">
|
||||||
|
<span className="text-sm font-mono text-zinc-300">v{v.version}</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-xs text-zinc-500">
|
||||||
|
{new Date(v.created_at).toLocaleString('zh-CN')}
|
||||||
|
</span>
|
||||||
|
{v.changelog && (
|
||||||
|
<span className="text-xs text-zinc-400">— {v.changelog}</span>
|
||||||
|
)}
|
||||||
|
{v.min_app_version && (
|
||||||
|
<span className="text-xs text-amber-400">最低版本: {v.min_app_version}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<pre className="text-xs text-zinc-400 bg-zinc-900 rounded p-2 overflow-x-auto max-h-32">
|
||||||
|
{v.system_prompt.substring(0, 300)}{v.system_prompt.length > 300 ? '...' : ''}
|
||||||
|
</pre>
|
||||||
|
<div className="mt-2 flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
navigator.clipboard.writeText(v.system_prompt)
|
||||||
|
}}
|
||||||
|
className="text-xs text-zinc-500 hover:text-white"
|
||||||
|
>
|
||||||
|
复制
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleRollback(selectedName, v.version)}
|
||||||
|
className="text-xs text-amber-500 hover:text-amber-400"
|
||||||
|
>
|
||||||
|
回退到此版本
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{versions.length === 0 && (
|
||||||
|
<EmptyState message="暂无版本历史" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Create Modal */}
|
||||||
|
{showCreate && (
|
||||||
|
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
|
||||||
|
<form onSubmit={handleCreate} className="bg-zinc-900 rounded-xl border border-zinc-700 p-6 w-full max-w-lg space-y-4">
|
||||||
|
<h2 className="text-lg font-semibold text-white">新建提示词模板</h2>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">名称</label>
|
||||||
|
<input name="name" required className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm" placeholder="my_prompt" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">分类</label>
|
||||||
|
<select name="category" className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm">
|
||||||
|
<option value="custom_system">系统提示词</option>
|
||||||
|
<option value="custom_extraction">提取提示词</option>
|
||||||
|
<option value="custom_compaction">压缩提示词</option>
|
||||||
|
<option value="custom_other">其他</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">描述</label>
|
||||||
|
<input name="description" className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm" placeholder="可选" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">系统提示词</label>
|
||||||
|
<textarea name="system_prompt" required rows={6} className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm font-mono" />
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 justify-end">
|
||||||
|
<button type="button" onClick={() => setShowCreate(false)} className="px-4 py-2 bg-zinc-700 text-white rounded-lg hover:bg-zinc-600 text-sm">取消</button>
|
||||||
|
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm">创建</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* New Version Modal */}
|
||||||
|
{showNewVersion && selectedName && (
|
||||||
|
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
|
||||||
|
<form onSubmit={handleNewVersion} className="bg-zinc-900 rounded-xl border border-zinc-700 p-6 w-full max-w-lg space-y-4">
|
||||||
|
<h2 className="text-lg font-semibold text-white">发布 {selectedName} 新版本</h2>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">系统提示词</label>
|
||||||
|
<textarea name="system_prompt" required rows={6} className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm font-mono" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm text-zinc-400 mb-1">变更说明</label>
|
||||||
|
<input name="changelog" className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm" placeholder="描述本次变更" />
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 justify-end">
|
||||||
|
<button type="button" onClick={() => setShowNewVersion(false)} className="px-4 py-2 bg-zinc-700 text-white rounded-lg hover:bg-zinc-600 text-sm">取消</button>
|
||||||
|
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm">发布</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
605
admin/src/app/(dashboard)/providers/page.tsx
Normal file
605
admin/src/app/(dashboard)/providers/page.tsx
Normal file
@@ -0,0 +1,605 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import useSWR from 'swr'
|
||||||
|
import {
|
||||||
|
Plus,
|
||||||
|
Loader2,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
Pencil,
|
||||||
|
Trash2,
|
||||||
|
KeyRound,
|
||||||
|
Power,
|
||||||
|
PowerOff,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogFooter,
|
||||||
|
DialogDescription,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import { TableSkeleton } from '@/components/ui/skeleton'
|
||||||
|
import { ErrorBanner, EmptyState } from '@/components/ui/state'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { ApiRequestError } from '@/lib/api-client'
|
||||||
|
import { formatDate, maskApiKey } from '@/lib/utils'
|
||||||
|
|
||||||
|
function formatTokens(tokens: number): string {
|
||||||
|
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`
|
||||||
|
if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}K`
|
||||||
|
return String(tokens)
|
||||||
|
}
|
||||||
|
import type { Provider, ProviderKey } from '@/lib/types'
|
||||||
|
|
||||||
|
const PAGE_SIZE = 20
|
||||||
|
|
||||||
|
interface ProviderForm {
|
||||||
|
name: string
|
||||||
|
display_name: string
|
||||||
|
base_url: string
|
||||||
|
api_protocol: 'openai' | 'anthropic'
|
||||||
|
api_key: string
|
||||||
|
enabled: boolean
|
||||||
|
rate_limit_rpm: string
|
||||||
|
rate_limit_tpm: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const emptyForm: ProviderForm = {
|
||||||
|
name: '',
|
||||||
|
display_name: '',
|
||||||
|
base_url: '',
|
||||||
|
api_protocol: 'openai',
|
||||||
|
api_key: '',
|
||||||
|
enabled: true,
|
||||||
|
rate_limit_rpm: '',
|
||||||
|
rate_limit_tpm: '',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ProvidersPage() {
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
// SWR for providers list
|
||||||
|
const { data, isLoading, mutate } = useSWR(
|
||||||
|
['providers', page],
|
||||||
|
() => api.providers.list({ page, page_size: PAGE_SIZE })
|
||||||
|
)
|
||||||
|
const providers = data?.items ?? []
|
||||||
|
const total = data?.total ?? 0
|
||||||
|
|
||||||
|
// 创建/编辑 Dialog
|
||||||
|
const [dialogOpen, setDialogOpen] = useState(false)
|
||||||
|
const [editTarget, setEditTarget] = useState<Provider | null>(null)
|
||||||
|
const [form, setForm] = useState<ProviderForm>(emptyForm)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
|
||||||
|
// 删除确认 Dialog
|
||||||
|
const [deleteTarget, setDeleteTarget] = useState<Provider | null>(null)
|
||||||
|
const [deleting, setDeleting] = useState(false)
|
||||||
|
|
||||||
|
// Key Pool 管理
|
||||||
|
const [keyPoolProvider, setKeyPoolProvider] = useState<Provider | null>(null)
|
||||||
|
const [showAddKey, setShowAddKey] = useState(false)
|
||||||
|
const [addKeyForm, setAddKeyForm] = useState({
|
||||||
|
key_label: '',
|
||||||
|
key_value: '',
|
||||||
|
priority: 0,
|
||||||
|
max_rpm: '',
|
||||||
|
max_tpm: '',
|
||||||
|
quota_reset_interval: '',
|
||||||
|
})
|
||||||
|
const [addingKey, setAddingKey] = useState(false)
|
||||||
|
|
||||||
|
// SWR for key pool — only fetches when dialog is open
|
||||||
|
const { data: providerKeys = [], isLoading: keysLoading, mutate: mutateKeys } = useSWR(
|
||||||
|
keyPoolProvider ? ['provider.keys', keyPoolProvider.id] : null,
|
||||||
|
() => api.providers.listKeys(keyPoolProvider!.id)
|
||||||
|
)
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
|
||||||
|
|
||||||
|
function openCreateDialog() {
|
||||||
|
setEditTarget(null)
|
||||||
|
setForm(emptyForm)
|
||||||
|
setDialogOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEditDialog(provider: Provider) {
|
||||||
|
setEditTarget(provider)
|
||||||
|
setForm({
|
||||||
|
name: provider.name,
|
||||||
|
display_name: provider.display_name,
|
||||||
|
base_url: provider.base_url,
|
||||||
|
api_protocol: provider.api_protocol,
|
||||||
|
api_key: provider.api_key || '',
|
||||||
|
enabled: provider.enabled,
|
||||||
|
rate_limit_rpm: provider.rate_limit_rpm?.toString() || '',
|
||||||
|
rate_limit_tpm: provider.rate_limit_tpm?.toString() || '',
|
||||||
|
})
|
||||||
|
setDialogOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSave() {
|
||||||
|
if (!form.name.trim() || !form.base_url.trim()) return
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
name: form.name.trim(),
|
||||||
|
display_name: form.display_name.trim(),
|
||||||
|
base_url: form.base_url.trim(),
|
||||||
|
api_protocol: form.api_protocol,
|
||||||
|
api_key: form.api_key.trim() || undefined,
|
||||||
|
enabled: form.enabled,
|
||||||
|
rate_limit_rpm: form.rate_limit_rpm ? parseInt(form.rate_limit_rpm, 10) : undefined,
|
||||||
|
rate_limit_tpm: form.rate_limit_tpm ? parseInt(form.rate_limit_tpm, 10) : undefined,
|
||||||
|
}
|
||||||
|
if (editTarget) {
|
||||||
|
await api.providers.update(editTarget.id, payload)
|
||||||
|
} else {
|
||||||
|
await api.providers.create(payload)
|
||||||
|
}
|
||||||
|
setDialogOpen(false)
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) setError(err.body.message)
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete() {
|
||||||
|
if (!deleteTarget) return
|
||||||
|
setDeleting(true)
|
||||||
|
try {
|
||||||
|
await api.providers.delete(deleteTarget.id)
|
||||||
|
setDeleteTarget(null)
|
||||||
|
mutate()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) setError(err.body.message)
|
||||||
|
} finally {
|
||||||
|
setDeleting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Key Pool 管理 ─────────────────────────────────────
|
||||||
|
|
||||||
|
function openKeyPool(provider: Provider) {
|
||||||
|
setKeyPoolProvider(provider)
|
||||||
|
setShowAddKey(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAddKey() {
|
||||||
|
if (!keyPoolProvider || !addKeyForm.key_label.trim() || !addKeyForm.key_value.trim()) return
|
||||||
|
setAddingKey(true)
|
||||||
|
try {
|
||||||
|
await api.providers.addKey(keyPoolProvider.id, {
|
||||||
|
key_label: addKeyForm.key_label.trim(),
|
||||||
|
key_value: addKeyForm.key_value.trim(),
|
||||||
|
priority: addKeyForm.priority,
|
||||||
|
max_rpm: addKeyForm.max_rpm ? parseInt(addKeyForm.max_rpm, 10) : undefined,
|
||||||
|
max_tpm: addKeyForm.max_tpm ? parseInt(addKeyForm.max_tpm, 10) : undefined,
|
||||||
|
quota_reset_interval: addKeyForm.quota_reset_interval.trim() || undefined,
|
||||||
|
})
|
||||||
|
setAddKeyForm({ key_label: '', key_value: '', priority: 0, max_rpm: '', max_tpm: '', quota_reset_interval: '' })
|
||||||
|
setShowAddKey(false)
|
||||||
|
mutateKeys()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) setError(err.body.message)
|
||||||
|
} finally {
|
||||||
|
setAddingKey(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleToggleKey(keyId: string, active: boolean) {
|
||||||
|
if (!keyPoolProvider) return
|
||||||
|
try {
|
||||||
|
await api.providers.toggleKey(keyPoolProvider.id, keyId, active)
|
||||||
|
mutateKeys()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) setError(err.body.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDeleteKey(keyId: string) {
|
||||||
|
if (!keyPoolProvider || !confirm('确认删除此 Key?')) return
|
||||||
|
try {
|
||||||
|
await api.providers.deleteKey(keyPoolProvider.id, keyId)
|
||||||
|
mutateKeys()
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) setError(err.body.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* 工具栏 */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div />
|
||||||
|
<Button onClick={openCreateDialog}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
新建服务商
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <ErrorBanner message={error} onDismiss={() => setError('')} />}
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<TableSkeleton rows={6} cols={9} hasToolbar={false} />
|
||||||
|
) : error ? null : providers.length === 0 ? (
|
||||||
|
<EmptyState />
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>名称</TableHead>
|
||||||
|
<TableHead>显示名</TableHead>
|
||||||
|
<TableHead>Base URL</TableHead>
|
||||||
|
<TableHead>协议</TableHead>
|
||||||
|
<TableHead>API Key</TableHead>
|
||||||
|
<TableHead>启用</TableHead>
|
||||||
|
<TableHead>RPM 限制</TableHead>
|
||||||
|
<TableHead>创建时间</TableHead>
|
||||||
|
<TableHead className="text-right">操作</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{providers.map((p) => (
|
||||||
|
<TableRow key={p.id}>
|
||||||
|
<TableCell className="font-medium">{p.name}</TableCell>
|
||||||
|
<TableCell>{p.display_name || '-'}</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground max-w-[200px] truncate">
|
||||||
|
{p.base_url}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={p.api_protocol === 'openai' ? 'default' : 'info'}>
|
||||||
|
{p.api_protocol}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{maskApiKey(p.api_key)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={p.enabled ? 'success' : 'secondary'}>
|
||||||
|
{p.enabled ? '是' : '否'}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">
|
||||||
|
{p.rate_limit_rpm ?? '-'}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{formatDate(p.created_at)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<div className="flex items-center justify-end gap-1">
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => openKeyPool(p)} title="Key Pool">
|
||||||
|
<KeyRound className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => openEditDialog(p)} title="编辑">
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => setDeleteTarget(p)} title="删除">
|
||||||
|
<Trash2 className="h-4 w-4 text-destructive" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between text-sm">
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
第 {page} 页 / 共 {totalPages} 页 ({total} 条)
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage(page - 1)}>
|
||||||
|
<ChevronLeft className="h-4 w-4 mr-1" />
|
||||||
|
上一页
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => setPage(page + 1)}>
|
||||||
|
下一页
|
||||||
|
<ChevronRight className="h-4 w-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 创建/编辑 Dialog */}
|
||||||
|
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{editTarget ? '编辑服务商' : '新建服务商'}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{editTarget ? '修改服务商配置' : '添加新的 AI 服务商'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-4 max-h-[60vh] overflow-y-auto scrollbar-thin pr-1">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>名称 *</Label>
|
||||||
|
<Input
|
||||||
|
value={form.name}
|
||||||
|
onChange={(e) => setForm({ ...form, name: e.target.value })}
|
||||||
|
placeholder="例如: openai"
|
||||||
|
disabled={!!editTarget}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>显示名</Label>
|
||||||
|
<Input
|
||||||
|
value={form.display_name}
|
||||||
|
onChange={(e) => setForm({ ...form, display_name: e.target.value })}
|
||||||
|
placeholder="例如: OpenAI"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Base URL *</Label>
|
||||||
|
<Input
|
||||||
|
value={form.base_url}
|
||||||
|
onChange={(e) => setForm({ ...form, base_url: e.target.value })}
|
||||||
|
placeholder="https://api.openai.com/v1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>API 协议</Label>
|
||||||
|
<Select value={form.api_protocol} onValueChange={(v) => setForm({ ...form, api_protocol: v as 'openai' | 'anthropic' })}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="openai">OpenAI</SelectItem>
|
||||||
|
<SelectItem value="anthropic">Anthropic</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>API Key</Label>
|
||||||
|
<Input
|
||||||
|
type="password"
|
||||||
|
value={form.api_key}
|
||||||
|
onChange={(e) => setForm({ ...form, api_key: e.target.value })}
|
||||||
|
placeholder={editTarget ? '留空则不修改' : 'sk-...'}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Switch
|
||||||
|
checked={form.enabled}
|
||||||
|
onCheckedChange={(v) => setForm({ ...form, enabled: v })}
|
||||||
|
/>
|
||||||
|
<Label>启用</Label>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>RPM 限制</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
value={form.rate_limit_rpm}
|
||||||
|
onChange={(e) => setForm({ ...form, rate_limit_rpm: e.target.value })}
|
||||||
|
placeholder="不限"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>TPM 限制</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
value={form.rate_limit_tpm}
|
||||||
|
onChange={(e) => setForm({ ...form, rate_limit_tpm: e.target.value })}
|
||||||
|
placeholder="不限"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
|
||||||
|
<Button onClick={handleSave} disabled={saving || !form.name.trim() || !form.base_url.trim()}>
|
||||||
|
{saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
保存
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* 删除确认 Dialog */}
|
||||||
|
<Dialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>确认删除</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
确定要删除服务商 "{deleteTarget?.display_name || deleteTarget?.name}" 吗?此操作不可撤销。
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setDeleteTarget(null)}>取消</Button>
|
||||||
|
<Button variant="destructive" onClick={handleDelete} disabled={deleting}>
|
||||||
|
{deleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* Key Pool 管理 Dialog */}
|
||||||
|
<Dialog open={!!keyPoolProvider} onOpenChange={() => setKeyPoolProvider(null)}>
|
||||||
|
<DialogContent className="max-w-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Key Pool 管理 — {keyPoolProvider?.display_name || keyPoolProvider?.name}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
管理此服务商的多个 API Key,实现智能轮转绕过限额。优先级数字越小越优先。
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="max-h-[50vh] overflow-y-auto scrollbar-thin">
|
||||||
|
{keysLoading ? (
|
||||||
|
<TableSkeleton rows={4} cols={8} hasToolbar={false} />
|
||||||
|
) : providerKeys.length === 0 && !showAddKey ? (
|
||||||
|
<div className="text-center py-8 text-muted-foreground text-sm">
|
||||||
|
<p>尚未配置 Key Pool</p>
|
||||||
|
<p className="mt-1 text-xs">将使用服务商主 API Key 作为回退</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>标签</TableHead>
|
||||||
|
<TableHead>优先级</TableHead>
|
||||||
|
<TableHead>RPM</TableHead>
|
||||||
|
<TableHead>TPM</TableHead>
|
||||||
|
<TableHead>状态</TableHead>
|
||||||
|
<TableHead>请求/Token</TableHead>
|
||||||
|
<TableHead>最后 429</TableHead>
|
||||||
|
<TableHead className="text-right">操作</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{providerKeys.map((k) => {
|
||||||
|
const isCooling = k.cooldown_until && new Date(k.cooldown_until) > new Date()
|
||||||
|
return (
|
||||||
|
<TableRow key={k.id} className={isCooling ? 'opacity-60' : ''}>
|
||||||
|
<TableCell className="font-medium">{k.key_label}</TableCell>
|
||||||
|
<TableCell>{k.priority}</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">{k.max_rpm ?? '-'}</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">{k.max_tpm ?? '-'}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={k.is_active ? 'success' : 'secondary'}>
|
||||||
|
{isCooling ? '冷却中' : k.is_active ? '活跃' : '禁用'}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-xs text-muted-foreground">
|
||||||
|
{k.total_requests} / {formatTokens(k.total_tokens)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-xs text-muted-foreground">
|
||||||
|
{k.last_429_at ? formatDate(k.last_429_at) : '-'}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<div className="flex items-center justify-end gap-1">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => handleToggleKey(k.id, !k.is_active)}
|
||||||
|
title={k.is_active ? '禁用' : '启用'}
|
||||||
|
>
|
||||||
|
{k.is_active ? <PowerOff className="h-3.5 w-3.5 text-amber-500" /> : <Power className="h-3.5 w-3.5 text-green-500" />}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => handleDeleteKey(k.id)}
|
||||||
|
title="删除"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5 text-destructive" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!showAddKey ? (
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setKeyPoolProvider(null)}>关闭</Button>
|
||||||
|
<Button onClick={() => setShowAddKey(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
添加 Key
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3 border-t pt-4">
|
||||||
|
<p className="text-sm font-medium">添加新 Key</p>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label className="text-xs">标签 *</Label>
|
||||||
|
<Input
|
||||||
|
value={addKeyForm.key_label}
|
||||||
|
onChange={(e) => setAddKeyForm({ ...addKeyForm, key_label: e.target.value })}
|
||||||
|
placeholder="如 zhipu-coding-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label className="text-xs">优先级</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
value={addKeyForm.priority}
|
||||||
|
onChange={(e) => setAddKeyForm({ ...addKeyForm, priority: parseInt(e.target.value, 10) || 0 })}
|
||||||
|
placeholder="0"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 space-y-1">
|
||||||
|
<Label className="text-xs">API Key *</Label>
|
||||||
|
<Input
|
||||||
|
type="password"
|
||||||
|
value={addKeyForm.key_value}
|
||||||
|
onChange={(e) => setAddKeyForm({ ...addKeyForm, key_value: e.target.value })}
|
||||||
|
placeholder="输入 API Key"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label className="text-xs">RPM 限额</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
value={addKeyForm.max_rpm}
|
||||||
|
onChange={(e) => setAddKeyForm({ ...addKeyForm, max_rpm: e.target.value })}
|
||||||
|
placeholder="不限"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label className="text-xs">TPM 限额</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
value={addKeyForm.max_tpm}
|
||||||
|
onChange={(e) => setAddKeyForm({ ...addKeyForm, max_tpm: e.target.value })}
|
||||||
|
placeholder="不限"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 space-y-1">
|
||||||
|
<Label className="text-xs">限额重置周期</Label>
|
||||||
|
<Input
|
||||||
|
value={addKeyForm.quota_reset_interval}
|
||||||
|
onChange={(e) => setAddKeyForm({ ...addKeyForm, quota_reset_interval: e.target.value })}
|
||||||
|
placeholder="如 5h, 1d(可选)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => { setShowAddKey(false); setAddKeyForm({ key_label: '', key_value: '', priority: 0, max_rpm: '', max_tpm: '', quota_reset_interval: '' }) }}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button onClick={handleAddKey} disabled={addingKey || !addKeyForm.key_label.trim() || !addKeyForm.key_value.trim()}>
|
||||||
|
{addingKey && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
添加
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
227
admin/src/app/(dashboard)/relay/page.tsx
Normal file
227
admin/src/app/(dashboard)/relay/page.tsx
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import useSWR from 'swr'
|
||||||
|
import {
|
||||||
|
Search,
|
||||||
|
Loader2,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
ChevronDown,
|
||||||
|
ChevronUp,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { ApiRequestError } from '@/lib/api-client'
|
||||||
|
import { formatDate, formatNumber, getSwrErrorMessage } from '@/lib/utils'
|
||||||
|
import { ErrorBanner, EmptyState } from '@/components/ui/state'
|
||||||
|
import { TableSkeleton } from '@/components/ui/skeleton'
|
||||||
|
import type { RelayTask } from '@/lib/types'
|
||||||
|
|
||||||
|
const PAGE_SIZE = 20
|
||||||
|
|
||||||
|
const statusVariants: Record<string, 'success' | 'info' | 'warning' | 'destructive' | 'secondary'> = {
|
||||||
|
queued: 'warning',
|
||||||
|
processing: 'info',
|
||||||
|
completed: 'success',
|
||||||
|
failed: 'destructive',
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusLabels: Record<string, string> = {
|
||||||
|
queued: '排队中',
|
||||||
|
processing: '处理中',
|
||||||
|
completed: '已完成',
|
||||||
|
failed: '失败',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function RelayPage() {
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [statusFilter, setStatusFilter] = useState<string>('all')
|
||||||
|
const [expandedId, setExpandedId] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const { data, error: swrError, isLoading } = useSWR(
|
||||||
|
['relay', page, statusFilter],
|
||||||
|
() => {
|
||||||
|
const params: Record<string, unknown> = { page, page_size: PAGE_SIZE }
|
||||||
|
if (statusFilter !== 'all') params.status = statusFilter
|
||||||
|
return api.relay.list(params)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
const tasks = data?.items ?? []
|
||||||
|
const total = data?.total ?? 0
|
||||||
|
const error = getSwrErrorMessage(swrError)
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
|
||||||
|
|
||||||
|
function toggleExpand(id: string) {
|
||||||
|
setExpandedId((prev) => (prev === id ? null : id))
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* 筛选 */}
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Select value={statusFilter} onValueChange={(v) => { setStatusFilter(v); setPage(1) }}>
|
||||||
|
<SelectTrigger className="w-[140px]">
|
||||||
|
<SelectValue placeholder="状态筛选" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">全部状态</SelectItem>
|
||||||
|
<SelectItem value="queued">排队中</SelectItem>
|
||||||
|
<SelectItem value="processing">处理中</SelectItem>
|
||||||
|
<SelectItem value="completed">已完成</SelectItem>
|
||||||
|
<SelectItem value="failed">失败</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <ErrorBanner message={error} onDismiss={() => {}} />}
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<TableSkeleton rows={6} cols={10} />
|
||||||
|
) : error ? null : tasks.length === 0 ? (
|
||||||
|
<EmptyState />
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead className="w-8" />
|
||||||
|
<TableHead>任务 ID</TableHead>
|
||||||
|
<TableHead>模型</TableHead>
|
||||||
|
<TableHead>状态</TableHead>
|
||||||
|
<TableHead>优先级</TableHead>
|
||||||
|
<TableHead>重试次数</TableHead>
|
||||||
|
<TableHead>Input Tokens</TableHead>
|
||||||
|
<TableHead>Output Tokens</TableHead>
|
||||||
|
<TableHead>错误信息</TableHead>
|
||||||
|
<TableHead>创建时间</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{tasks.map((task) => (
|
||||||
|
<>
|
||||||
|
<TableRow key={task.id} className="cursor-pointer" onClick={() => toggleExpand(task.id)}>
|
||||||
|
<TableCell>
|
||||||
|
{expandedId === task.id ? (
|
||||||
|
<ChevronUp className="h-4 w-4 text-muted-foreground" />
|
||||||
|
) : (
|
||||||
|
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs">
|
||||||
|
{task.id.slice(0, 8)}...
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs">
|
||||||
|
{task.model_id}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={statusVariants[task.status] || 'secondary'}>
|
||||||
|
{statusLabels[task.status] || task.status}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">{task.priority}</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">{task.attempt_count}</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{formatNumber(task.input_tokens)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{formatNumber(task.output_tokens)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="max-w-[200px] truncate text-xs text-destructive">
|
||||||
|
{task.error_message || '-'}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||||
|
{formatDate(task.created_at)}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
{expandedId === task.id && (
|
||||||
|
<TableRow key={`${task.id}-detail`}>
|
||||||
|
<TableCell colSpan={10} className="bg-muted/20 px-8 py-4">
|
||||||
|
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">任务 ID</p>
|
||||||
|
<p className="font-mono text-xs">{task.id}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">账号 ID</p>
|
||||||
|
<p className="font-mono text-xs">{task.account_id}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">服务商 ID</p>
|
||||||
|
<p className="font-mono text-xs">{task.provider_id}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">模型 ID</p>
|
||||||
|
<p className="font-mono text-xs">{task.model_id}</p>
|
||||||
|
</div>
|
||||||
|
{task.queued_at && (
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">排队时间</p>
|
||||||
|
<p className="font-mono text-xs">{formatDate(task.queued_at)}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{task.started_at && (
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">开始时间</p>
|
||||||
|
<p className="font-mono text-xs">{formatDate(task.started_at)}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{task.completed_at && (
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">完成时间</p>
|
||||||
|
<p className="font-mono text-xs">{formatDate(task.completed_at)}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{task.error_message && (
|
||||||
|
<div className="col-span-2">
|
||||||
|
<p className="text-muted-foreground">错误信息</p>
|
||||||
|
<p className="text-xs text-destructive mt-1">{task.error_message}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between text-sm">
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
第 {page} 页 / 共 {totalPages} 页 ({total} 条)
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage(page - 1)}>
|
||||||
|
<ChevronLeft className="h-4 w-4 mr-1" />
|
||||||
|
上一页
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => setPage(page + 1)}>
|
||||||
|
下一页
|
||||||
|
<ChevronRight className="h-4 w-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
330
admin/src/app/(dashboard)/usage/page.tsx
Normal file
330
admin/src/app/(dashboard)/usage/page.tsx
Normal file
@@ -0,0 +1,330 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import useSWR from 'swr'
|
||||||
|
import { Zap, Monitor, Smartphone } from 'lucide-react'
|
||||||
|
import {
|
||||||
|
LineChart,
|
||||||
|
Line,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
CartesianGrid,
|
||||||
|
Tooltip,
|
||||||
|
ResponsiveContainer,
|
||||||
|
BarChart,
|
||||||
|
Bar,
|
||||||
|
Legend,
|
||||||
|
} from 'recharts'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { ErrorBanner, EmptyState } from '@/components/ui/state'
|
||||||
|
import { TableSkeleton, ChartSkeleton } from '@/components/ui/skeleton'
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from '@/components/ui/table'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { formatNumber } from '@/lib/utils'
|
||||||
|
import type { UsageRecord, UsageByModel, ModelUsageStat, DailyUsageStat } from '@/lib/types'
|
||||||
|
|
||||||
|
export default function UsagePage() {
|
||||||
|
const [days, setDays] = useState(7)
|
||||||
|
const [activeTab, setActiveTab] = useState('relay')
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
// 4 parallel SWR calls — each loads independently
|
||||||
|
const { data: dailyData = [], isLoading: dailyLoading } = useSWR(
|
||||||
|
['usage.daily', days],
|
||||||
|
() => api.usage.daily({ days })
|
||||||
|
)
|
||||||
|
const { data: modelData = [], isLoading: modelLoading } = useSWR(
|
||||||
|
['usage.byModel', days],
|
||||||
|
() => api.usage.byModel({ days })
|
||||||
|
)
|
||||||
|
const { data: telemetryModels = [] } = useSWR(
|
||||||
|
['telemetry.modelStats'],
|
||||||
|
() => api.telemetry.modelStats()
|
||||||
|
)
|
||||||
|
const { data: telemetryDaily = [] } = useSWR(
|
||||||
|
['telemetry.dailyStats', days],
|
||||||
|
() => api.telemetry.dailyStats({ days })
|
||||||
|
)
|
||||||
|
|
||||||
|
const relayLoading = dailyLoading || modelLoading
|
||||||
|
const telemetryLoading = !telemetryModels.length && !telemetryDaily.length && (dailyLoading || modelLoading)
|
||||||
|
|
||||||
|
// === Relay 用量图表数据 ===
|
||||||
|
|
||||||
|
const relayLineData = dailyData.map((r) => ({
|
||||||
|
day: r.day.slice(5),
|
||||||
|
Input: r.input_tokens,
|
||||||
|
Output: r.output_tokens,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const relayBarData = modelData.map((r) => ({
|
||||||
|
model: r.model_id,
|
||||||
|
请求量: r.count,
|
||||||
|
Input: r.input_tokens,
|
||||||
|
Output: r.output_tokens,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const relayTotalInput = dailyData.reduce((s, r) => s + r.input_tokens, 0)
|
||||||
|
const relayTotalOutput = dailyData.reduce((s, r) => s + r.output_tokens, 0)
|
||||||
|
const relayTotalRequests = dailyData.reduce((s, r) => s + r.count, 0)
|
||||||
|
|
||||||
|
// === 遥测图表数据 ===
|
||||||
|
|
||||||
|
const telemetryLineData = telemetryDaily.map((r) => ({
|
||||||
|
day: r.day.slice(5),
|
||||||
|
Input: r.input_tokens,
|
||||||
|
Output: r.output_tokens,
|
||||||
|
设备数: r.unique_devices,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const telemetryTotalInput = telemetryDaily.reduce((s, r) => s + r.input_tokens, 0)
|
||||||
|
const telemetryTotalOutput = telemetryDaily.reduce((s, r) => s + r.output_tokens, 0)
|
||||||
|
const telemetryTotalRequests = telemetryDaily.reduce((s, r) => s + r.request_count, 0)
|
||||||
|
|
||||||
|
// === 合计 ===
|
||||||
|
|
||||||
|
const totalInput = relayTotalInput + telemetryTotalInput
|
||||||
|
const totalOutput = relayTotalOutput + telemetryTotalOutput
|
||||||
|
const totalRequests = relayTotalRequests + telemetryTotalRequests
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{error && <ErrorBanner message={error} onDismiss={() => setError('')} />}
|
||||||
|
{/* 时间范围 */}
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<span className="text-sm text-muted-foreground">时间范围:</span>
|
||||||
|
<Select value={String(days)} onValueChange={(v) => setDays(Number(v))}>
|
||||||
|
<SelectTrigger className="w-[140px]">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="7">最近 7 天</SelectItem>
|
||||||
|
<SelectItem value="30">最近 30 天</SelectItem>
|
||||||
|
<SelectItem value="90">最近 90 天</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 汇总统计 — render immediately, use 0 while loading */}
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-5">
|
||||||
|
<Card>
|
||||||
|
<CardContent className="p-6">
|
||||||
|
<p className="text-sm text-muted-foreground">总请求数</p>
|
||||||
|
<p className="mt-1 text-2xl font-bold text-foreground">
|
||||||
|
{formatNumber(totalRequests)}
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
<Card>
|
||||||
|
<CardContent className="p-6">
|
||||||
|
<p className="text-sm text-muted-foreground">总 Input Tokens</p>
|
||||||
|
<p className="mt-1 text-2xl font-bold text-blue-400">
|
||||||
|
{formatNumber(totalInput)}
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
<Card>
|
||||||
|
<CardContent className="p-6">
|
||||||
|
<p className="text-sm text-muted-foreground">总 Output Tokens</p>
|
||||||
|
<p className="mt-1 text-2xl font-bold text-orange-400">
|
||||||
|
{formatNumber(totalOutput)}
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
<Card>
|
||||||
|
<CardContent className="p-6">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Monitor className="h-4 w-4 text-green-400" />
|
||||||
|
<p className="text-sm text-muted-foreground">中转请求</p>
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-2xl font-bold text-green-400">
|
||||||
|
{formatNumber(relayTotalRequests)}
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
<Card>
|
||||||
|
<CardContent className="p-6">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Smartphone className="h-4 w-4 text-purple-400" />
|
||||||
|
<p className="text-sm text-muted-foreground">桌面端调用</p>
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-2xl font-bold text-purple-400">
|
||||||
|
{formatNumber(telemetryTotalRequests)}
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tab 切换 */}
|
||||||
|
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="relay">
|
||||||
|
<Monitor className="h-4 w-4 mr-1" />
|
||||||
|
中转用量
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="telemetry">
|
||||||
|
<Smartphone className="h-4 w-4 mr-1" />
|
||||||
|
桌面端遥测
|
||||||
|
</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
|
||||||
|
{/* Relay 用量 Tab */}
|
||||||
|
<TabsContent value="relay" className="space-y-6">
|
||||||
|
{relayLoading ? (
|
||||||
|
<>
|
||||||
|
<ChartSkeleton height={320} />
|
||||||
|
<ChartSkeleton height={280} />
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2 text-base">
|
||||||
|
<Zap className="h-4 w-4 text-primary" />
|
||||||
|
中转 Token 用量趋势
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{relayLineData.length > 0 ? (
|
||||||
|
<ResponsiveContainer width="100%" height={320}>
|
||||||
|
<LineChart data={relayLineData}>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#1E293B" />
|
||||||
|
<XAxis dataKey="day" tick={{ fontSize: 12, fill: '#94A3B8' }} axisLine={{ stroke: '#1E293B' }} />
|
||||||
|
<YAxis tick={{ fontSize: 12, fill: '#94A3B8' }} axisLine={{ stroke: '#1E293B' }} />
|
||||||
|
<Tooltip contentStyle={{ backgroundColor: '#0F172A', border: '1px solid #1E293B', borderRadius: '8px', color: '#F8FAFC', fontSize: '12px' }} />
|
||||||
|
<Legend wrapperStyle={{ fontSize: '12px', color: '#94A3B8' }} />
|
||||||
|
<Line type="monotone" dataKey="Input" stroke="#3B82F6" strokeWidth={2} dot={false} />
|
||||||
|
<Line type="monotone" dataKey="Output" stroke="#F97316" strokeWidth={2} dot={false} />
|
||||||
|
</LineChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
) : (
|
||||||
|
<EmptyState message="暂无中转数据" />
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-base">中转按模型分布</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{relayBarData.length > 0 ? (
|
||||||
|
<ResponsiveContainer width="100%" height={Math.max(200, relayBarData.length * 40)}>
|
||||||
|
<BarChart data={relayBarData} layout="vertical">
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#1E293B" />
|
||||||
|
<XAxis type="number" tick={{ fontSize: 12, fill: '#94A3B8' }} axisLine={{ stroke: '#1E293B' }} />
|
||||||
|
<YAxis type="category" dataKey="model" tick={{ fontSize: 12, fill: '#94A3B8' }} axisLine={{ stroke: '#1E293B' }} width={120} />
|
||||||
|
<Tooltip contentStyle={{ backgroundColor: '#0F172A', border: '1px solid #1E293B', borderRadius: '8px', color: '#F8FAFC', fontSize: '12px' }} />
|
||||||
|
<Legend wrapperStyle={{ fontSize: '12px', color: '#94A3B8' }} />
|
||||||
|
<Bar dataKey="Input" fill="#3B82F6" radius={[0, 2, 2, 0]} />
|
||||||
|
<Bar dataKey="Output" fill="#F97316" radius={[0, 2, 2, 0]} />
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
) : (
|
||||||
|
<EmptyState />
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
{/* 遥测 Tab */}
|
||||||
|
<TabsContent value="telemetry" className="space-y-6">
|
||||||
|
{telemetryLoading ? (
|
||||||
|
<>
|
||||||
|
<ChartSkeleton height={320} />
|
||||||
|
<TableSkeleton rows={5} cols={6} hasToolbar={false} />
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2 text-base">
|
||||||
|
<Smartphone className="h-4 w-4 text-purple-400" />
|
||||||
|
桌面端 Token 用量趋势
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{telemetryLineData.length > 0 ? (
|
||||||
|
<ResponsiveContainer width="100%" height={320}>
|
||||||
|
<LineChart data={telemetryLineData}>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#1E293B" />
|
||||||
|
<XAxis dataKey="day" tick={{ fontSize: 12, fill: '#94A3B8' }} axisLine={{ stroke: '#1E293B' }} />
|
||||||
|
<YAxis tick={{ fontSize: 12, fill: '#94A3B8' }} axisLine={{ stroke: '#1E293B' }} />
|
||||||
|
<Tooltip contentStyle={{ backgroundColor: '#0F172A', border: '1px solid #1E293B', borderRadius: '8px', color: '#F8FAFC', fontSize: '12px' }} />
|
||||||
|
<Legend wrapperStyle={{ fontSize: '12px', color: '#94A3B8' }} />
|
||||||
|
<Line type="monotone" dataKey="Input" stroke="#3B82F6" strokeWidth={2} dot={false} />
|
||||||
|
<Line type="monotone" dataKey="Output" stroke="#F97316" strokeWidth={2} dot={false} />
|
||||||
|
</LineChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
) : (
|
||||||
|
<EmptyState message="暂无桌面端遥测数据(需要桌面端上报)" />
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-base">桌面端按模型统计</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{telemetryModels.length > 0 ? (
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>模型</TableHead>
|
||||||
|
<TableHead className="text-right">请求数</TableHead>
|
||||||
|
<TableHead className="text-right">Input Tokens</TableHead>
|
||||||
|
<TableHead className="text-right">Output Tokens</TableHead>
|
||||||
|
<TableHead className="text-right">平均延迟</TableHead>
|
||||||
|
<TableHead className="text-right">成功率</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{telemetryModels.map((stat) => (
|
||||||
|
<TableRow key={stat.model_id}>
|
||||||
|
<TableCell className="font-mono text-sm">{stat.model_id}</TableCell>
|
||||||
|
<TableCell className="text-right">{formatNumber(stat.request_count)}</TableCell>
|
||||||
|
<TableCell className="text-right text-blue-400">{formatNumber(stat.input_tokens)}</TableCell>
|
||||||
|
<TableCell className="text-right text-orange-400">{formatNumber(stat.output_tokens)}</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
{stat.avg_latency_ms !== null ? `${Math.round(stat.avg_latency_ms)}ms` : '-'}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<Badge variant={stat.success_rate >= 0.95 ? 'default' : 'destructive'}>
|
||||||
|
{(stat.success_rate * 100).toFixed(1)}%
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
) : (
|
||||||
|
<EmptyState />
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
66
admin/src/app/globals.css
Normal file
66
admin/src/app/globals.css
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
:root {
|
||||||
|
--background: 222 47% 5%;
|
||||||
|
--foreground: 210 40% 98%;
|
||||||
|
--card: 222 47% 8%;
|
||||||
|
--card-foreground: 210 40% 98%;
|
||||||
|
--primary: 142 71% 45%;
|
||||||
|
--primary-foreground: 222 47% 5%;
|
||||||
|
--muted: 217 33% 17%;
|
||||||
|
--muted-foreground: 215 20% 65%;
|
||||||
|
--accent: 215 28% 23%;
|
||||||
|
--accent-foreground: 210 40% 98%;
|
||||||
|
--destructive: 0 84% 60%;
|
||||||
|
--destructive-foreground: 210 40% 98%;
|
||||||
|
--border: 217 33% 17%;
|
||||||
|
--input: 217 33% 17%;
|
||||||
|
--ring: 142 71% 45%;
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
border-color: hsl(var(--border));
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
background-color: hsl(var(--background));
|
||||||
|
color: hsl(var(--foreground));
|
||||||
|
font-family: 'Inter', system-ui, -apple-system, sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer utilities {
|
||||||
|
.scrollbar-thin {
|
||||||
|
scrollbar-width: thin;
|
||||||
|
scrollbar-color: hsl(var(--muted)) transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.scrollbar-thin::-webkit-scrollbar {
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.scrollbar-thin::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.scrollbar-thin::-webkit-scrollbar-thumb {
|
||||||
|
background-color: hsl(var(--muted));
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.scrollbar-thin::-webkit-scrollbar-thumb:hover {
|
||||||
|
background-color: hsl(var(--accent));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer components {
|
||||||
|
.glass-card {
|
||||||
|
@apply bg-card/80 backdrop-blur-sm border border-border rounded-lg;
|
||||||
|
}
|
||||||
|
}
|
||||||
4
admin/src/app/icon.svg
Normal file
4
admin/src/app/icon.svg
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
|
||||||
|
<rect width="32" height="32" rx="6" fill="#0f172a"/>
|
||||||
|
<text x="16" y="22" font-family="system-ui, sans-serif" font-size="16" font-weight="700" fill="#60a5fa" text-anchor="middle">Z</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 282 B |
30
admin/src/app/layout.tsx
Normal file
30
admin/src/app/layout.tsx
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import type { Metadata } from 'next'
|
||||||
|
import { SWRProvider } from '@/lib/swr-provider'
|
||||||
|
import './globals.css'
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: 'ZCLAW Admin',
|
||||||
|
description: 'ZCLAW AI Agent 管理平台',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function RootLayout({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<html lang="zh-CN" className="dark">
|
||||||
|
<head>
|
||||||
|
<link
|
||||||
|
href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap"
|
||||||
|
rel="stylesheet"
|
||||||
|
/>
|
||||||
|
</head>
|
||||||
|
<body className="min-h-screen bg-background font-sans antialiased">
|
||||||
|
<SWRProvider>
|
||||||
|
{children}
|
||||||
|
</SWRProvider>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
241
admin/src/app/login/page.tsx
Normal file
241
admin/src/app/login/page.tsx
Normal file
@@ -0,0 +1,241 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState, type FormEvent } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { Lock, User, Loader2, Eye, EyeOff, ShieldCheck } from 'lucide-react'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { login } from '@/lib/auth'
|
||||||
|
import { ApiRequestError } from '@/lib/api-client'
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const [username, setUsername] = useState('')
|
||||||
|
const [password, setPassword] = useState('')
|
||||||
|
const [totpCode, setTotpCode] = useState('')
|
||||||
|
const [showPassword, setShowPassword] = useState(false)
|
||||||
|
const [needTotp, setNeedTotp] = useState(false)
|
||||||
|
const [remember, setRemember] = useState(false)
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
async function handleSubmit(e: FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
setError('')
|
||||||
|
|
||||||
|
if (!username.trim()) {
|
||||||
|
setError('请输入用户名')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!password.trim()) {
|
||||||
|
setError('请输入密码')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
try {
|
||||||
|
const res = await api.auth.login({
|
||||||
|
username: username.trim(),
|
||||||
|
password,
|
||||||
|
totp_code: totpCode.trim() || undefined,
|
||||||
|
})
|
||||||
|
login(res.token, res.account)
|
||||||
|
router.replace('/')
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiRequestError) {
|
||||||
|
const msg = err.body.message || ''
|
||||||
|
// 后端返回 "需要 TOTP" 时显示 TOTP 输入框
|
||||||
|
if (msg.includes('TOTP') || msg.includes('totp') || msg.includes('2FA') || msg.includes('验证码') || err.status === 403) {
|
||||||
|
setNeedTotp(true)
|
||||||
|
setError(msg || '请输入两步验证码')
|
||||||
|
} else {
|
||||||
|
setError(msg || '登录失败,请检查用户名和密码')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setError('网络错误,请稍后重试')
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen">
|
||||||
|
{/* 左侧品牌区域 */}
|
||||||
|
<div className="hidden lg:flex lg:w-1/2 relative overflow-hidden bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
|
||||||
|
{/* 装饰性背景 */}
|
||||||
|
<div className="absolute inset-0">
|
||||||
|
<div className="absolute top-1/4 left-1/4 w-96 h-96 bg-green-500/5 rounded-full blur-3xl" />
|
||||||
|
<div className="absolute bottom-1/4 right-1/4 w-64 h-64 bg-green-500/8 rounded-full blur-3xl" />
|
||||||
|
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] border border-green-500/10 rounded-full" />
|
||||||
|
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[400px] h-[400px] border border-green-500/10 rounded-full" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 品牌内容 */}
|
||||||
|
<div className="relative z-10 flex flex-col items-center justify-center w-full p-12">
|
||||||
|
<div className="text-center">
|
||||||
|
<h1 className="text-6xl font-bold tracking-tight text-foreground mb-4">
|
||||||
|
ZCLAW
|
||||||
|
</h1>
|
||||||
|
<p className="text-xl text-muted-foreground font-light">
|
||||||
|
AI Agent 管理平台
|
||||||
|
</p>
|
||||||
|
<div className="mt-8 flex items-center justify-center gap-2">
|
||||||
|
<div className="h-px w-12 bg-green-500/50" />
|
||||||
|
<div className="w-2 h-2 rounded-full bg-green-500" />
|
||||||
|
<div className="h-px w-12 bg-green-500/50" />
|
||||||
|
</div>
|
||||||
|
<p className="mt-6 text-sm text-muted-foreground/60 max-w-sm">
|
||||||
|
统一管理 AI 服务商、模型配置、API 密钥、用量监控与系统配置
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 右侧登录表单 */}
|
||||||
|
<div className="flex w-full lg:w-1/2 items-center justify-center p-8">
|
||||||
|
<div className="w-full max-w-sm space-y-8">
|
||||||
|
{/* 移动端 Logo */}
|
||||||
|
<div className="lg:hidden text-center">
|
||||||
|
<h1 className="text-4xl font-bold tracking-tight text-foreground mb-2">
|
||||||
|
ZCLAW
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">AI Agent 管理平台</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h2 className="text-2xl font-semibold text-foreground">登录</h2>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">
|
||||||
|
输入您的账号信息以继续
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
{/* 用户名 */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label
|
||||||
|
htmlFor="username"
|
||||||
|
className="text-sm font-medium text-foreground"
|
||||||
|
>
|
||||||
|
用户名
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<User className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<input
|
||||||
|
id="username"
|
||||||
|
type="text"
|
||||||
|
placeholder="请输入用户名"
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-transparent pl-10 pr-3 py-2 text-sm shadow-sm transition-colors duration-200 placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||||
|
autoComplete="username"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 密码 */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label
|
||||||
|
htmlFor="password"
|
||||||
|
className="text-sm font-medium text-foreground"
|
||||||
|
>
|
||||||
|
密码
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
type={showPassword ? 'text' : 'password'}
|
||||||
|
placeholder="请输入密码"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-transparent pl-10 pr-10 py-2 text-sm shadow-sm transition-colors duration-200 placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||||
|
autoComplete="current-password"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowPassword(!showPassword)}
|
||||||
|
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors duration-200 cursor-pointer"
|
||||||
|
>
|
||||||
|
{showPassword ? (
|
||||||
|
<EyeOff className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<Eye className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* TOTP 验证码 */}
|
||||||
|
{needTotp && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label
|
||||||
|
htmlFor="totp"
|
||||||
|
className="text-sm font-medium text-foreground"
|
||||||
|
>
|
||||||
|
两步验证码
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<ShieldCheck className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<input
|
||||||
|
id="totp"
|
||||||
|
type="text"
|
||||||
|
placeholder="请输入 6 位验证码"
|
||||||
|
value={totpCode}
|
||||||
|
onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
|
||||||
|
maxLength={6}
|
||||||
|
className="flex h-10 w-full rounded-md border border-input bg-transparent pl-10 pr-3 py-2 text-sm shadow-sm transition-colors duration-200 placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring tracking-widest"
|
||||||
|
autoComplete="one-time-code"
|
||||||
|
inputMode="numeric"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
请使用身份验证器 App(如 Google Authenticator)扫描二维码后生成的验证码
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 记住我 */}
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
id="remember"
|
||||||
|
type="checkbox"
|
||||||
|
checked={remember}
|
||||||
|
onChange={(e) => setRemember(e.target.checked)}
|
||||||
|
className="h-4 w-4 rounded border-input bg-transparent accent-primary cursor-pointer"
|
||||||
|
/>
|
||||||
|
<label
|
||||||
|
htmlFor="remember"
|
||||||
|
className="text-sm text-muted-foreground cursor-pointer select-none"
|
||||||
|
>
|
||||||
|
记住我
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 错误信息 */}
|
||||||
|
{error && (
|
||||||
|
<div className="rounded-md bg-destructive/10 border border-destructive/20 px-4 py-3 text-sm text-destructive">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 登录按钮 */}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="flex h-10 w-full items-center justify-center rounded-md bg-primary text-primary-foreground font-medium text-sm shadow-sm transition-colors duration-200 hover:bg-primary-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 cursor-pointer"
|
||||||
|
>
|
||||||
|
{loading ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
登录中...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
'登录'
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
113
admin/src/components/auth-guard.tsx
Normal file
113
admin/src/components/auth-guard.tsx
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect, useState, useCallback, type ReactNode } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { isAuthenticated, getAccount, clearAuth } from '@/lib/auth'
|
||||||
|
import { api, ApiRequestError } from '@/lib/api-client'
|
||||||
|
import type { AccountPublic } from '@/lib/types'
|
||||||
|
import { AlertTriangle, RefreshCw } from 'lucide-react'
|
||||||
|
|
||||||
|
interface AuthGuardProps {
|
||||||
|
children: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AuthGuard({ children }: AuthGuardProps) {
|
||||||
|
const router = useRouter()
|
||||||
|
const [authorized, setAuthorized] = useState(false)
|
||||||
|
const [account, setAccount] = useState<AccountPublic | null>(null)
|
||||||
|
const [verifying, setVerifying] = useState(true)
|
||||||
|
const [connectionError, setConnectionError] = useState(false)
|
||||||
|
|
||||||
|
const verifyAuth = useCallback(async () => {
|
||||||
|
setVerifying(true)
|
||||||
|
setConnectionError(false)
|
||||||
|
|
||||||
|
if (!isAuthenticated()) {
|
||||||
|
setVerifying(false)
|
||||||
|
router.replace('/login')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Already authorized? Skip re-verification on remount (e.g. Next.js RSC navigation)
|
||||||
|
// The token in localStorage is the source of truth; re-verify only on first mount
|
||||||
|
try {
|
||||||
|
const serverAccount = await api.auth.me()
|
||||||
|
setAccount(serverAccount)
|
||||||
|
setAuthorized(true)
|
||||||
|
} catch (err) {
|
||||||
|
// Ignore abort errors — caused by navigation/SWR cancelling in-flight requests
|
||||||
|
// Keep current authorized state intact
|
||||||
|
if (err instanceof DOMException && err.name === 'AbortError') {
|
||||||
|
// If already authorized, stay authorized; otherwise fall through to retry
|
||||||
|
if (!authorized) {
|
||||||
|
// First mount was aborted — use cached account from localStorage
|
||||||
|
const cachedAccount = getAccount()
|
||||||
|
if (cachedAccount) {
|
||||||
|
setAccount(cachedAccount)
|
||||||
|
setAuthorized(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Only clear auth on actual authentication failures (401/403)
|
||||||
|
// Network errors, timeouts should NOT destroy the session
|
||||||
|
if (err instanceof ApiRequestError && (err.status === 401 || err.status === 403)) {
|
||||||
|
clearAuth()
|
||||||
|
router.replace('/login')
|
||||||
|
} else {
|
||||||
|
// Transient error — show retry UI, keep token in localStorage
|
||||||
|
setConnectionError(true)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setVerifying(false)
|
||||||
|
}
|
||||||
|
}, [router, authorized])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
verifyAuth()
|
||||||
|
}, [verifyAuth])
|
||||||
|
|
||||||
|
if (verifying) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-screen w-screen items-center justify-center bg-background">
|
||||||
|
<div className="h-8 w-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (connectionError) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-screen w-screen flex-col items-center justify-center gap-4 bg-background">
|
||||||
|
<AlertTriangle className="h-12 w-12 text-yellow-500" />
|
||||||
|
<h2 className="text-lg font-semibold text-foreground">连接中断</h2>
|
||||||
|
<p className="text-sm text-muted-foreground">无法连接到服务器,请检查网络后重试</p>
|
||||||
|
<button
|
||||||
|
onClick={verifyAuth}
|
||||||
|
className="mt-2 inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors cursor-pointer"
|
||||||
|
>
|
||||||
|
<RefreshCw className="h-4 w-4" />
|
||||||
|
重新连接
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!authorized) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>{children}</>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAuth() {
|
||||||
|
const [account, setAccount] = useState<AccountPublic | null>(null)
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const acc = getAccount()
|
||||||
|
setAccount(acc)
|
||||||
|
setLoading(false)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return { account, loading, isAuthenticated: isAuthenticated() }
|
||||||
|
}
|
||||||
42
admin/src/components/ui/badge.tsx
Normal file
42
admin/src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import * as React from 'react'
|
||||||
|
import { cva, type VariantProps } from 'class-variance-authority'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const badgeVariants = cva(
|
||||||
|
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default:
|
||||||
|
'border-transparent bg-primary/15 text-primary',
|
||||||
|
secondary:
|
||||||
|
'border-transparent bg-muted text-muted-foreground',
|
||||||
|
destructive:
|
||||||
|
'border-transparent bg-destructive/15 text-destructive',
|
||||||
|
outline:
|
||||||
|
'text-foreground border-border',
|
||||||
|
success:
|
||||||
|
'border-transparent bg-green-500/15 text-green-400',
|
||||||
|
warning:
|
||||||
|
'border-transparent bg-yellow-500/15 text-yellow-400',
|
||||||
|
info:
|
||||||
|
'border-transparent bg-blue-500/15 text-blue-400',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: 'default',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
export interface BadgeProps
|
||||||
|
extends React.HTMLAttributes<HTMLDivElement>,
|
||||||
|
VariantProps<typeof badgeVariants> {}
|
||||||
|
|
||||||
|
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||||
|
return (
|
||||||
|
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Badge, badgeVariants }
|
||||||
56
admin/src/components/ui/button.tsx
Normal file
56
admin/src/components/ui/button.tsx
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import * as React from 'react'
|
||||||
|
import { cva, type VariantProps } from 'class-variance-authority'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const buttonVariants = cva(
|
||||||
|
'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50',
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default:
|
||||||
|
'bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm',
|
||||||
|
secondary:
|
||||||
|
'bg-muted text-muted-foreground hover:bg-accent hover:text-accent-foreground',
|
||||||
|
destructive:
|
||||||
|
'bg-destructive text-destructive-foreground hover:bg-red-600 shadow-sm',
|
||||||
|
outline:
|
||||||
|
'border border-border bg-transparent hover:bg-accent hover:text-accent-foreground',
|
||||||
|
ghost:
|
||||||
|
'hover:bg-accent hover:text-accent-foreground',
|
||||||
|
link:
|
||||||
|
'text-primary underline-offset-4 hover:underline',
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: 'h-9 px-4 py-2',
|
||||||
|
sm: 'h-8 rounded-md px-3 text-xs',
|
||||||
|
lg: 'h-10 rounded-md px-8',
|
||||||
|
icon: 'h-9 w-9',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: 'default',
|
||||||
|
size: 'default',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
export interface ButtonProps
|
||||||
|
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||||
|
VariantProps<typeof buttonVariants> {}
|
||||||
|
|
||||||
|
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||||
|
({ className, variant, size, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
|
ref={ref}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
Button.displayName = 'Button'
|
||||||
|
|
||||||
|
export { Button, buttonVariants }
|
||||||
75
admin/src/components/ui/card.tsx
Normal file
75
admin/src/components/ui/card.tsx
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import * as React from 'react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const Card = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.HTMLAttributes<HTMLDivElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'rounded-lg border border-border bg-card text-card-foreground shadow-sm',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
Card.displayName = 'Card'
|
||||||
|
|
||||||
|
const CardHeader = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.HTMLAttributes<HTMLDivElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className={cn('flex flex-col space-y-1.5 p-6', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
CardHeader.displayName = 'CardHeader'
|
||||||
|
|
||||||
|
const CardTitle = React.forwardRef<
|
||||||
|
HTMLParagraphElement,
|
||||||
|
React.HTMLAttributes<HTMLHeadingElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<h3
|
||||||
|
ref={ref}
|
||||||
|
className={cn('font-semibold leading-none tracking-tight', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
CardTitle.displayName = 'CardTitle'
|
||||||
|
|
||||||
|
const CardDescription = React.forwardRef<
|
||||||
|
HTMLParagraphElement,
|
||||||
|
React.HTMLAttributes<HTMLParagraphElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<p
|
||||||
|
ref={ref}
|
||||||
|
className={cn('text-sm text-muted-foreground', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
CardDescription.displayName = 'CardDescription'
|
||||||
|
|
||||||
|
const CardContent = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.HTMLAttributes<HTMLDivElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
|
||||||
|
))
|
||||||
|
CardContent.displayName = 'CardContent'
|
||||||
|
|
||||||
|
const CardFooter = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.HTMLAttributes<HTMLDivElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className={cn('flex items-center p-6 pt-0', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
CardFooter.displayName = 'CardFooter'
|
||||||
|
|
||||||
|
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
|
||||||
118
admin/src/components/ui/dialog.tsx
Normal file
118
admin/src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import * as React from 'react'
|
||||||
|
import * as DialogPrimitive from '@radix-ui/react-dialog'
|
||||||
|
import { X } from 'lucide-react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const Dialog = DialogPrimitive.Root
|
||||||
|
const DialogTrigger = DialogPrimitive.Trigger
|
||||||
|
const DialogPortal = DialogPrimitive.Portal
|
||||||
|
const DialogClose = DialogPrimitive.Close
|
||||||
|
|
||||||
|
const DialogOverlay = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<DialogPrimitive.Overlay
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'fixed inset-0 z-50 bg-black/60 backdrop-blur-sm',
|
||||||
|
'data-[state=open]:animate-in data-[state=closed]:animate-out',
|
||||||
|
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
|
||||||
|
|
||||||
|
const DialogContent = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
||||||
|
>(({ className, children, ...props }, ref) => (
|
||||||
|
<DialogPortal>
|
||||||
|
<DialogOverlay />
|
||||||
|
<DialogPrimitive.Content
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%]',
|
||||||
|
'gap-4 border border-border bg-card p-6 shadow-lg duration-200',
|
||||||
|
'data-[state=open]:animate-in data-[state=closed]:animate-out',
|
||||||
|
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||||
|
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||||
|
'data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%]',
|
||||||
|
'data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]',
|
||||||
|
'rounded-lg',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
<span className="sr-only">Close</span>
|
||||||
|
</DialogPrimitive.Close>
|
||||||
|
</DialogPrimitive.Content>
|
||||||
|
</DialogPortal>
|
||||||
|
))
|
||||||
|
DialogContent.displayName = DialogPrimitive.Content.displayName
|
||||||
|
|
||||||
|
const DialogHeader = ({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||||
|
<div
|
||||||
|
className={cn('flex flex-col space-y-1.5 text-center sm:text-left', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
DialogHeader.displayName = 'DialogHeader'
|
||||||
|
|
||||||
|
const DialogFooter = ({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||||
|
<div
|
||||||
|
className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
DialogFooter.displayName = 'DialogFooter'
|
||||||
|
|
||||||
|
const DialogTitle = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<DialogPrimitive.Title
|
||||||
|
ref={ref}
|
||||||
|
className={cn('text-lg font-semibold leading-none tracking-tight', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
DialogTitle.displayName = DialogPrimitive.Title.displayName
|
||||||
|
|
||||||
|
const DialogDescription = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<DialogPrimitive.Description
|
||||||
|
ref={ref}
|
||||||
|
className={cn('text-sm text-muted-foreground', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
DialogDescription.displayName = DialogPrimitive.Description.displayName
|
||||||
|
|
||||||
|
export {
|
||||||
|
Dialog,
|
||||||
|
DialogPortal,
|
||||||
|
DialogOverlay,
|
||||||
|
DialogClose,
|
||||||
|
DialogTrigger,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogFooter,
|
||||||
|
DialogTitle,
|
||||||
|
DialogDescription,
|
||||||
|
}
|
||||||
28
admin/src/components/ui/input.tsx
Normal file
28
admin/src/components/ui/input.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import * as React from 'react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
export interface InputProps
|
||||||
|
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||||
|
|
||||||
|
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||||
|
({ className, type, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type={type}
|
||||||
|
className={cn(
|
||||||
|
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors duration-200',
|
||||||
|
'file:border-0 file:bg-transparent file:text-sm file:font-medium',
|
||||||
|
'placeholder:text-muted-foreground',
|
||||||
|
'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
|
||||||
|
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
ref={ref}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
Input.displayName = 'Input'
|
||||||
|
|
||||||
|
export { Input }
|
||||||
23
admin/src/components/ui/label.tsx
Normal file
23
admin/src/components/ui/label.tsx
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import * as React from 'react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
export interface LabelProps
|
||||||
|
extends React.LabelHTMLAttributes<HTMLLabelElement> {}
|
||||||
|
|
||||||
|
const Label = React.forwardRef<HTMLLabelElement, LabelProps>(
|
||||||
|
({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<label
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
Label.displayName = 'Label'
|
||||||
|
|
||||||
|
export { Label }
|
||||||
100
admin/src/components/ui/select.tsx
Normal file
100
admin/src/components/ui/select.tsx
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import * as React from 'react'
|
||||||
|
import * as SelectPrimitive from '@radix-ui/react-select'
|
||||||
|
import { Check, ChevronDown } from 'lucide-react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const Select = SelectPrimitive.Root
|
||||||
|
const SelectGroup = SelectPrimitive.Group
|
||||||
|
const SelectValue = SelectPrimitive.Value
|
||||||
|
|
||||||
|
const SelectTrigger = React.forwardRef<
|
||||||
|
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||||
|
>(({ className, children, ...props }, ref) => (
|
||||||
|
<SelectPrimitive.Trigger
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background',
|
||||||
|
'placeholder:text-muted-foreground',
|
||||||
|
'focus:outline-none focus:ring-1 focus:ring-ring',
|
||||||
|
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
|
'[&>span]:line-clamp-1',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<SelectPrimitive.Icon asChild>
|
||||||
|
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||||
|
</SelectPrimitive.Icon>
|
||||||
|
</SelectPrimitive.Trigger>
|
||||||
|
))
|
||||||
|
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
|
||||||
|
|
||||||
|
const SelectContent = React.forwardRef<
|
||||||
|
React.ElementRef<typeof SelectPrimitive.Content>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||||
|
>(({ className, children, position = 'popper', ...props }, ref) => (
|
||||||
|
<SelectPrimitive.Portal>
|
||||||
|
<SelectPrimitive.Content
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card text-foreground shadow-md',
|
||||||
|
'data-[state=open]:animate-in data-[state=closed]:animate-out',
|
||||||
|
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||||
|
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||||
|
position === 'popper' &&
|
||||||
|
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
position={position}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<SelectPrimitive.Viewport
|
||||||
|
className={cn(
|
||||||
|
'p-1',
|
||||||
|
position === 'popper' &&
|
||||||
|
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</SelectPrimitive.Viewport>
|
||||||
|
</SelectPrimitive.Content>
|
||||||
|
</SelectPrimitive.Portal>
|
||||||
|
))
|
||||||
|
SelectContent.displayName = SelectPrimitive.Content.displayName
|
||||||
|
|
||||||
|
const SelectItem = React.forwardRef<
|
||||||
|
React.ElementRef<typeof SelectPrimitive.Item>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||||
|
>(({ className, children, ...props }, ref) => (
|
||||||
|
<SelectPrimitive.Item
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none',
|
||||||
|
'focus:bg-accent focus:text-accent-foreground',
|
||||||
|
'data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||||
|
<SelectPrimitive.ItemIndicator>
|
||||||
|
<Check className="h-4 w-4" />
|
||||||
|
</SelectPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||||
|
</SelectPrimitive.Item>
|
||||||
|
))
|
||||||
|
SelectItem.displayName = SelectPrimitive.Item.displayName
|
||||||
|
|
||||||
|
export {
|
||||||
|
Select,
|
||||||
|
SelectGroup,
|
||||||
|
SelectValue,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
}
|
||||||
30
admin/src/components/ui/separator.tsx
Normal file
30
admin/src/components/ui/separator.tsx
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import * as React from 'react'
|
||||||
|
import * as SeparatorPrimitive from '@radix-ui/react-separator'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const Separator = React.forwardRef<
|
||||||
|
React.ElementRef<typeof SeparatorPrimitive.Root>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
|
||||||
|
>(
|
||||||
|
(
|
||||||
|
{ className, orientation = 'horizontal', decorative = true, ...props },
|
||||||
|
ref,
|
||||||
|
) => (
|
||||||
|
<SeparatorPrimitive.Root
|
||||||
|
ref={ref}
|
||||||
|
decorative={decorative}
|
||||||
|
orientation={orientation}
|
||||||
|
className={cn(
|
||||||
|
'shrink-0 bg-border',
|
||||||
|
orientation === 'horizontal' ? 'h-[1px] w-full' : 'h-full w-[1px]',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
)
|
||||||
|
Separator.displayName = SeparatorPrimitive.Root.displayName
|
||||||
|
|
||||||
|
export { Separator }
|
||||||
115
admin/src/components/ui/skeleton.tsx
Normal file
115
admin/src/components/ui/skeleton.tsx
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
// ============================================================
|
||||||
|
// Skeleton 组件 — 替代全屏 spinner 的骨架屏
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
function SkeletonBase({ className }: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'animate-pulse rounded-md bg-muted',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 表格骨架屏 */
|
||||||
|
export function TableSkeleton({
|
||||||
|
rows = 5,
|
||||||
|
cols = 5,
|
||||||
|
hasToolbar = true,
|
||||||
|
}: {
|
||||||
|
rows?: number
|
||||||
|
cols?: number
|
||||||
|
hasToolbar?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{hasToolbar && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<SkeletonBase className="h-9 w-[200px]" />
|
||||||
|
<SkeletonBase className="h-9 w-[120px]" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="rounded-md border border-border overflow-hidden">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="border-b border-border bg-muted/30 px-4 py-3">
|
||||||
|
<div className="flex gap-4">
|
||||||
|
{Array.from({ length: cols }).map((_, i) => (
|
||||||
|
<SkeletonBase
|
||||||
|
key={i}
|
||||||
|
className={cn(
|
||||||
|
'h-4',
|
||||||
|
i === 0 ? 'w-[120px]' : i === cols - 1 ? 'w-[80px]' : 'w-[100px]',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/* Rows */}
|
||||||
|
{Array.from({ length: rows }).map((_, rowIdx) => (
|
||||||
|
<div
|
||||||
|
key={rowIdx}
|
||||||
|
className={cn(
|
||||||
|
'px-4 py-3',
|
||||||
|
rowIdx < rows - 1 && 'border-b border-border',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex gap-4">
|
||||||
|
{Array.from({ length: cols }).map((_, colIdx) => (
|
||||||
|
<SkeletonBase
|
||||||
|
key={colIdx}
|
||||||
|
className={cn(
|
||||||
|
'h-4',
|
||||||
|
colIdx === 0 ? 'w-[120px]' : colIdx === cols - 1 ? 'w-[80px]' : 'w-[100px]',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{/* Pagination */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<SkeletonBase className="h-4 w-[140px]" />
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<SkeletonBase className="h-8 w-[80px]" />
|
||||||
|
<SkeletonBase className="h-8 w-[80px]" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 统计卡片骨架屏 */
|
||||||
|
export function StatsSkeleton({ count = 4 }: { count?: number }) {
|
||||||
|
return (
|
||||||
|
<div className={`grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-${count}`}>
|
||||||
|
{Array.from({ length: count }).map((_, i) => (
|
||||||
|
<div key={i} className="rounded-lg border border-border p-6">
|
||||||
|
<SkeletonBase className="h-4 w-[80px]" />
|
||||||
|
<SkeletonBase className="mt-2 h-8 w-[100px]" />
|
||||||
|
<SkeletonBase className="mt-1 h-3 w-[120px]" />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 图表骨架屏 */
|
||||||
|
export function ChartSkeleton({ height }: { height?: number }) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-border">
|
||||||
|
<div className="border-b border-border px-6 py-4">
|
||||||
|
<SkeletonBase className="h-5 w-[140px]" />
|
||||||
|
</div>
|
||||||
|
<div className="p-6">
|
||||||
|
<SkeletonBase className="w-full" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { SkeletonBase as Skeleton }
|
||||||
63
admin/src/components/ui/state.tsx
Normal file
63
admin/src/components/ui/state.tsx
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { AlertCircle, Inbox } from 'lucide-react'
|
||||||
|
|
||||||
|
/** 统一的错误提示横幅 */
|
||||||
|
export function ErrorBanner({
|
||||||
|
message,
|
||||||
|
onDismiss,
|
||||||
|
}: {
|
||||||
|
message: string
|
||||||
|
onDismiss?: () => void
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-md bg-destructive/10 border border-destructive/20 px-4 py-3 text-sm text-destructive flex items-center gap-2">
|
||||||
|
<AlertCircle className="h-4 w-4 shrink-0" />
|
||||||
|
<span className="flex-1">{message}</span>
|
||||||
|
{onDismiss && (
|
||||||
|
<button
|
||||||
|
onClick={onDismiss}
|
||||||
|
className="underline cursor-pointer shrink-0"
|
||||||
|
>
|
||||||
|
关闭
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 统一的空状态占位 */
|
||||||
|
export function EmptyState({
|
||||||
|
message = '暂无数据',
|
||||||
|
}: {
|
||||||
|
message?: string
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-64 flex-col items-center justify-center gap-2 text-muted-foreground">
|
||||||
|
<Inbox className="h-8 w-8" />
|
||||||
|
<span className="text-sm">{message}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 统一的加载失败提示 + 重试 */
|
||||||
|
export function ErrorRetry({
|
||||||
|
message = '请求失败,请重试',
|
||||||
|
onRetry,
|
||||||
|
}: {
|
||||||
|
message?: string
|
||||||
|
onRetry: () => void
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-64 flex-col items-center justify-center gap-3 text-muted-foreground">
|
||||||
|
<AlertCircle className="h-8 w-8 text-destructive" />
|
||||||
|
<span className="text-sm">{message}</span>
|
||||||
|
<button
|
||||||
|
onClick={onRetry}
|
||||||
|
className="rounded-md bg-primary px-4 py-2 text-sm text-primary-foreground hover:bg-primary/90 transition-colors cursor-pointer"
|
||||||
|
>
|
||||||
|
重新加载
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
32
admin/src/components/ui/switch.tsx
Normal file
32
admin/src/components/ui/switch.tsx
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import * as React from 'react'
|
||||||
|
import * as SwitchPrimitive from '@radix-ui/react-switch'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const Switch = React.forwardRef<
|
||||||
|
React.ElementRef<typeof SwitchPrimitive.Root>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<SwitchPrimitive.Root
|
||||||
|
className={cn(
|
||||||
|
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors duration-200',
|
||||||
|
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
|
||||||
|
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
|
'data-[state=checked]:bg-primary data-[state=unchecked]:bg-input',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
ref={ref}
|
||||||
|
>
|
||||||
|
<SwitchPrimitive.Thumb
|
||||||
|
className={cn(
|
||||||
|
'pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform duration-200',
|
||||||
|
'data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</SwitchPrimitive.Root>
|
||||||
|
))
|
||||||
|
Switch.displayName = SwitchPrimitive.Root.displayName
|
||||||
|
|
||||||
|
export { Switch }
|
||||||
119
admin/src/components/ui/table.tsx
Normal file
119
admin/src/components/ui/table.tsx
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
import * as React from 'react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const Table = React.forwardRef<
|
||||||
|
HTMLTableElement,
|
||||||
|
React.HTMLAttributes<HTMLTableElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<div className="relative w-full overflow-auto scrollbar-thin">
|
||||||
|
<table
|
||||||
|
ref={ref}
|
||||||
|
className={cn('w-full caption-bottom text-sm', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
Table.displayName = 'Table'
|
||||||
|
|
||||||
|
const TableHeader = React.forwardRef<
|
||||||
|
HTMLTableSectionElement,
|
||||||
|
React.HTMLAttributes<HTMLTableSectionElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} />
|
||||||
|
))
|
||||||
|
TableHeader.displayName = 'TableHeader'
|
||||||
|
|
||||||
|
const TableBody = React.forwardRef<
|
||||||
|
HTMLTableSectionElement,
|
||||||
|
React.HTMLAttributes<HTMLTableSectionElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<tbody
|
||||||
|
ref={ref}
|
||||||
|
className={cn('[&_tr:last-child]:border-0', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableBody.displayName = 'TableBody'
|
||||||
|
|
||||||
|
const TableFooter = React.forwardRef<
|
||||||
|
HTMLTableSectionElement,
|
||||||
|
React.HTMLAttributes<HTMLTableSectionElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<tfoot
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'border-t bg-muted/50 font-medium [&>tr]:last:border-b-0',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableFooter.displayName = 'TableFooter'
|
||||||
|
|
||||||
|
const TableRow = React.forwardRef<
|
||||||
|
HTMLTableRowElement,
|
||||||
|
React.HTMLAttributes<HTMLTableRowElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<tr
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'border-b border-border transition-colors duration-200 hover:bg-muted/50',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableRow.displayName = 'TableRow'
|
||||||
|
|
||||||
|
const TableHead = React.forwardRef<
|
||||||
|
HTMLTableCellElement,
|
||||||
|
React.ThHTMLAttributes<HTMLTableCellElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<th
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'h-10 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableHead.displayName = 'TableHead'
|
||||||
|
|
||||||
|
const TableCell = React.forwardRef<
|
||||||
|
HTMLTableCellElement,
|
||||||
|
React.TdHTMLAttributes<HTMLTableCellElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<td
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'p-4 align-middle [&:has([role=checkbox])]:pr-0',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableCell.displayName = 'TableCell'
|
||||||
|
|
||||||
|
const TableCaption = React.forwardRef<
|
||||||
|
HTMLTableCaptionElement,
|
||||||
|
React.HTMLAttributes<HTMLTableCaptionElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<caption
|
||||||
|
ref={ref}
|
||||||
|
className={cn('mt-4 text-sm text-muted-foreground', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableCaption.displayName = 'TableCaption'
|
||||||
|
|
||||||
|
export {
|
||||||
|
Table,
|
||||||
|
TableHeader,
|
||||||
|
TableBody,
|
||||||
|
TableFooter,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
|
TableCell,
|
||||||
|
TableCaption,
|
||||||
|
}
|
||||||
57
admin/src/components/ui/tabs.tsx
Normal file
57
admin/src/components/ui/tabs.tsx
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import * as React from 'react'
|
||||||
|
import * as TabsPrimitive from '@radix-ui/react-tabs'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const Tabs = TabsPrimitive.Root
|
||||||
|
|
||||||
|
const TabsList = React.forwardRef<
|
||||||
|
React.ElementRef<typeof TabsPrimitive.List>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<TabsPrimitive.List
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TabsList.displayName = TabsPrimitive.List.displayName
|
||||||
|
|
||||||
|
const TabsTrigger = React.forwardRef<
|
||||||
|
React.ElementRef<typeof TabsPrimitive.Trigger>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<TabsPrimitive.Trigger
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all duration-200',
|
||||||
|
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
|
||||||
|
'disabled:pointer-events-none disabled:opacity-50',
|
||||||
|
'data-[state=active]:bg-card data-[state=active]:text-foreground data-[state=active]:shadow',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
|
||||||
|
|
||||||
|
const TabsContent = React.forwardRef<
|
||||||
|
React.ElementRef<typeof TabsPrimitive.Content>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<TabsPrimitive.Content
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
'mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TabsContent.displayName = TabsPrimitive.Content.displayName
|
||||||
|
|
||||||
|
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
||||||
31
admin/src/components/ui/tooltip.tsx
Normal file
31
admin/src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import * as React from 'react'
|
||||||
|
import * as TooltipPrimitive from '@radix-ui/react-tooltip'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const TooltipProvider = TooltipPrimitive.Provider
|
||||||
|
const Tooltip = TooltipPrimitive.Root
|
||||||
|
const TooltipTrigger = TooltipPrimitive.Trigger
|
||||||
|
|
||||||
|
const TooltipContent = React.forwardRef<
|
||||||
|
React.ElementRef<typeof TooltipPrimitive.Content>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
|
||||||
|
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||||
|
<TooltipPrimitive.Content
|
||||||
|
ref={ref}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
'z-50 overflow-hidden rounded-md bg-card border border-border px-3 py-1.5 text-sm text-foreground shadow-md',
|
||||||
|
'animate-in fade-in-0 zoom-in-95',
|
||||||
|
'data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95',
|
||||||
|
'data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2',
|
||||||
|
'data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TooltipContent.displayName = TooltipPrimitive.Content.displayName
|
||||||
|
|
||||||
|
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||||
16
admin/src/hooks/use-debounce.ts
Normal file
16
admin/src/hooks/use-debounce.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
// ============================================================
|
||||||
|
// useDebounce — 防抖 hook
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
|
||||||
|
export function useDebounce<T>(value: T, delay = 300): T {
|
||||||
|
const [debouncedValue, setDebouncedValue] = useState<T>(value)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = setTimeout(() => setDebouncedValue(value), delay)
|
||||||
|
return () => clearTimeout(handler)
|
||||||
|
}, [value, delay])
|
||||||
|
|
||||||
|
return debouncedValue
|
||||||
|
}
|
||||||
535
admin/src/lib/api-client.ts
Normal file
535
admin/src/lib/api-client.ts
Normal file
@@ -0,0 +1,535 @@
|
|||||||
|
// ============================================================
|
||||||
|
// ZCLAW SaaS Admin — 类型化 HTTP 客户端
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { getToken, login as saveToken, logout, getAccount } from './auth'
|
||||||
|
import type {
|
||||||
|
AccountPublic,
|
||||||
|
AgentTemplate,
|
||||||
|
ApiError,
|
||||||
|
ConfigItem,
|
||||||
|
CreateTokenRequest,
|
||||||
|
DashboardStats,
|
||||||
|
DailyUsageStat,
|
||||||
|
LoginRequest,
|
||||||
|
LoginResponse,
|
||||||
|
Model,
|
||||||
|
ModelUsageStat,
|
||||||
|
OperationLog,
|
||||||
|
PaginatedResponse,
|
||||||
|
PromptTemplate,
|
||||||
|
PromptVersion,
|
||||||
|
Provider,
|
||||||
|
ProviderKey,
|
||||||
|
RelayTask,
|
||||||
|
TokenInfo,
|
||||||
|
UsageByModel,
|
||||||
|
UsageRecord,
|
||||||
|
} from './types'
|
||||||
|
|
||||||
|
// ── 错误类 ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export class ApiRequestError extends Error {
|
||||||
|
constructor(
|
||||||
|
public status: number,
|
||||||
|
public body: ApiError,
|
||||||
|
) {
|
||||||
|
super(body.message || `Request failed with status ${status}`)
|
||||||
|
this.name = 'ApiRequestError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 基础请求 ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
const BASE_URL = process.env.NEXT_PUBLIC_SAAS_API_URL || '/api/v1'
|
||||||
|
|
||||||
|
const DEFAULT_TIMEOUT_MS = 10_000
|
||||||
|
const MAX_RETRIES = 2
|
||||||
|
|
||||||
|
function sleep(ms: number): Promise<void> {
|
||||||
|
return new Promise(resolve => setTimeout(resolve, ms))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 判断是否为可重试的网络错误(不含 AbortError) */
|
||||||
|
function isRetryableNetworkError(err: unknown): boolean {
|
||||||
|
// AbortError 不重试:可能是组件卸载或路由切换导致的外部取消
|
||||||
|
if (err instanceof DOMException && err.name === 'AbortError') return false
|
||||||
|
if (err instanceof TypeError) {
|
||||||
|
const msg = (err as TypeError).message
|
||||||
|
return msg.includes('Failed to fetch') || msg.includes('NetworkError') || msg.includes('ECONNREFUSED')
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 尝试刷新 Token,成功返回新 token,失败返回 null */
|
||||||
|
async function tryRefreshToken(): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
const token = getToken()
|
||||||
|
if (!token) return null
|
||||||
|
|
||||||
|
const res = await fetch(`${BASE_URL}/auth/refresh`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!res.ok) return null
|
||||||
|
|
||||||
|
const data = await res.json()
|
||||||
|
const newToken = data.token as string
|
||||||
|
const account = getAccount()
|
||||||
|
if (account && newToken) {
|
||||||
|
saveToken(newToken, account)
|
||||||
|
}
|
||||||
|
return newToken
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function request<T>(
|
||||||
|
method: string,
|
||||||
|
path: string,
|
||||||
|
body?: unknown,
|
||||||
|
_isRetry = false,
|
||||||
|
externalSignal?: AbortSignal,
|
||||||
|
): Promise<T> {
|
||||||
|
let lastError: unknown
|
||||||
|
|
||||||
|
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
||||||
|
// Merge external signal (e.g. from SWR) with a timeout signal
|
||||||
|
const signals: AbortSignal[] = [AbortSignal.timeout(DEFAULT_TIMEOUT_MS)]
|
||||||
|
if (externalSignal) signals.push(externalSignal)
|
||||||
|
const signal = signals.length === 1 ? signals[0] : AbortSignal.any(signals)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const token = getToken()
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
}
|
||||||
|
if (token) {
|
||||||
|
headers['Authorization'] = `Bearer ${token}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(`${BASE_URL}${path}`, {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
body: body ? JSON.stringify(body) : undefined,
|
||||||
|
signal,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 401: 尝试刷新 Token 后重试
|
||||||
|
if (res.status === 401 && !_isRetry) {
|
||||||
|
const newToken = await tryRefreshToken()
|
||||||
|
if (newToken) {
|
||||||
|
return request<T>(method, path, body, true)
|
||||||
|
}
|
||||||
|
logout()
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.location.href = '/login'
|
||||||
|
}
|
||||||
|
throw new ApiRequestError(401, { error: 'unauthorized', message: '登录已过期,请重新登录' })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
let errorBody: ApiError
|
||||||
|
try {
|
||||||
|
errorBody = await res.json()
|
||||||
|
} catch {
|
||||||
|
errorBody = { error: 'unknown', message: `请求失败 (${res.status})` }
|
||||||
|
}
|
||||||
|
throw new ApiRequestError(res.status, errorBody)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 204 No Content
|
||||||
|
if (res.status === 204) {
|
||||||
|
return undefined as T
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.json() as Promise<T>
|
||||||
|
} catch (err) {
|
||||||
|
// API 错误和外部取消的 AbortError 直接抛出,不重试
|
||||||
|
if (err instanceof ApiRequestError) throw err
|
||||||
|
if (err instanceof DOMException && err.name === 'AbortError') throw err
|
||||||
|
|
||||||
|
lastError = err
|
||||||
|
|
||||||
|
// 仅对可重试的网络错误重试
|
||||||
|
if (attempt < MAX_RETRIES && isRetryableNetworkError(err)) {
|
||||||
|
await sleep(1000 * Math.pow(2, attempt))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw lastError
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── API 客户端 ────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
// ── 认证 ──────────────────────────────────────────────
|
||||||
|
auth: {
|
||||||
|
async login(data: LoginRequest): Promise<LoginResponse> {
|
||||||
|
return request<LoginResponse>('POST', '/auth/login', data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async register(data: {
|
||||||
|
username: string
|
||||||
|
password: string
|
||||||
|
email: string
|
||||||
|
display_name?: string
|
||||||
|
}): Promise<LoginResponse> {
|
||||||
|
return request<LoginResponse>('POST', '/auth/register', data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async me(): Promise<AccountPublic> {
|
||||||
|
return request<AccountPublic>('GET', '/auth/me')
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── 账号管理 ──────────────────────────────────────────
|
||||||
|
accounts: {
|
||||||
|
async list(params?: {
|
||||||
|
page?: number
|
||||||
|
page_size?: number
|
||||||
|
search?: string
|
||||||
|
role?: string
|
||||||
|
status?: string
|
||||||
|
}): Promise<PaginatedResponse<AccountPublic>> {
|
||||||
|
const qs = buildQueryString(params)
|
||||||
|
return request<PaginatedResponse<AccountPublic>>('GET', `/accounts${qs}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async get(id: string): Promise<AccountPublic> {
|
||||||
|
return request<AccountPublic>('GET', `/accounts/${id}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async update(
|
||||||
|
id: string,
|
||||||
|
data: Partial<Pick<AccountPublic, 'display_name' | 'email' | 'role'>>,
|
||||||
|
): Promise<AccountPublic> {
|
||||||
|
return request<AccountPublic>('PATCH', `/accounts/${id}`, data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async updateStatus(
|
||||||
|
id: string,
|
||||||
|
data: { status: AccountPublic['status'] },
|
||||||
|
): Promise<void> {
|
||||||
|
return request<void>('PATCH', `/accounts/${id}/status`, data)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── 服务商管理 ────────────────────────────────────────
|
||||||
|
providers: {
|
||||||
|
async list(params?: {
|
||||||
|
page?: number
|
||||||
|
page_size?: number
|
||||||
|
}): Promise<PaginatedResponse<Provider>> {
|
||||||
|
const qs = buildQueryString(params)
|
||||||
|
return request<PaginatedResponse<Provider>>('GET', `/providers${qs}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async create(data: Partial<Omit<Provider, 'id' | 'created_at' | 'updated_at'>>): Promise<Provider> {
|
||||||
|
return request<Provider>('POST', '/providers', data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async update(
|
||||||
|
id: string,
|
||||||
|
data: Partial<Omit<Provider, 'id' | 'created_at' | 'updated_at'>>,
|
||||||
|
): Promise<Provider> {
|
||||||
|
return request<Provider>('PATCH', `/providers/${id}`, data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async delete(id: string): Promise<void> {
|
||||||
|
return request<void>('DELETE', `/providers/${id}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
// Key Pool 管理
|
||||||
|
async listKeys(providerId: string): Promise<ProviderKey[]> {
|
||||||
|
return request<ProviderKey[]>('GET', `/providers/${providerId}/keys`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async addKey(providerId: string, data: {
|
||||||
|
key_label: string
|
||||||
|
key_value: string
|
||||||
|
priority?: number
|
||||||
|
max_rpm?: number
|
||||||
|
max_tpm?: number
|
||||||
|
quota_reset_interval?: string
|
||||||
|
}): Promise<{ ok: boolean; key_id: string }> {
|
||||||
|
return request<{ ok: boolean; key_id: string }>('POST', `/providers/${providerId}/keys`, data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async toggleKey(providerId: string, keyId: string, active: boolean): Promise<{ ok: boolean }> {
|
||||||
|
return request<{ ok: boolean }>('PUT', `/providers/${providerId}/keys/${keyId}/toggle`, { active })
|
||||||
|
},
|
||||||
|
|
||||||
|
async deleteKey(providerId: string, keyId: string): Promise<{ ok: boolean }> {
|
||||||
|
return request<{ ok: boolean }>('DELETE', `/providers/${providerId}/keys/${keyId}`)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── 模型管理 ──────────────────────────────────────────
|
||||||
|
models: {
|
||||||
|
async list(params?: {
|
||||||
|
page?: number
|
||||||
|
page_size?: number
|
||||||
|
provider_id?: string
|
||||||
|
}): Promise<PaginatedResponse<Model>> {
|
||||||
|
const qs = buildQueryString(params)
|
||||||
|
return request<PaginatedResponse<Model>>('GET', `/models${qs}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async create(data: Partial<Omit<Model, 'id'>>): Promise<Model> {
|
||||||
|
return request<Model>('POST', '/models', data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async update(id: string, data: Partial<Omit<Model, 'id'>>): Promise<Model> {
|
||||||
|
return request<Model>('PATCH', `/models/${id}`, data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async delete(id: string): Promise<void> {
|
||||||
|
return request<void>('DELETE', `/models/${id}`)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── API 密钥 ──────────────────────────────────────────
|
||||||
|
tokens: {
|
||||||
|
async list(params?: {
|
||||||
|
page?: number
|
||||||
|
page_size?: number
|
||||||
|
}): Promise<PaginatedResponse<TokenInfo>> {
|
||||||
|
const qs = buildQueryString(params)
|
||||||
|
return request<PaginatedResponse<TokenInfo>>('GET', `/keys${qs}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async create(data: CreateTokenRequest): Promise<TokenInfo> {
|
||||||
|
return request<TokenInfo>('POST', '/keys', data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async revoke(id: string): Promise<void> {
|
||||||
|
return request<void>('DELETE', `/keys/${id}`)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── 用量统计 ──────────────────────────────────────────
|
||||||
|
usage: {
|
||||||
|
async daily(params?: { days?: number }): Promise<UsageRecord[]> {
|
||||||
|
const qs = buildQueryString({ ...params, group_by: 'day' })
|
||||||
|
const result = await request<{ by_day: UsageRecord[] }>('GET', `/usage${qs}`)
|
||||||
|
return result.by_day || []
|
||||||
|
},
|
||||||
|
|
||||||
|
async byModel(params?: { days?: number }): Promise<UsageByModel[]> {
|
||||||
|
const qs = buildQueryString({ ...params, group_by: 'model' })
|
||||||
|
const result = await request<{ by_model: UsageByModel[] }>('GET', `/usage${qs}`)
|
||||||
|
return result.by_model || []
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── 中转任务 ──────────────────────────────────────────
|
||||||
|
relay: {
|
||||||
|
async list(params?: {
|
||||||
|
page?: number
|
||||||
|
page_size?: number
|
||||||
|
status?: string
|
||||||
|
}): Promise<PaginatedResponse<RelayTask>> {
|
||||||
|
const qs = buildQueryString(params)
|
||||||
|
return request<PaginatedResponse<RelayTask>>('GET', `/relay/tasks${qs}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async get(id: string): Promise<RelayTask> {
|
||||||
|
return request<RelayTask>('GET', `/relay/tasks/${id}`)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── 系统配置 ──────────────────────────────────────────
|
||||||
|
config: {
|
||||||
|
async list(params?: {
|
||||||
|
category?: string
|
||||||
|
page?: number
|
||||||
|
page_size?: number
|
||||||
|
}): Promise<ConfigItem[]> {
|
||||||
|
const qs = buildQueryString(params)
|
||||||
|
const result = await request<PaginatedResponse<ConfigItem>>('GET', `/config/items${qs}`)
|
||||||
|
return result.items
|
||||||
|
},
|
||||||
|
|
||||||
|
async update(id: string, data: { value: string | number | boolean }): Promise<ConfigItem> {
|
||||||
|
return request<ConfigItem>('PATCH', `/config/items/${id}`, data)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── 操作日志 ──────────────────────────────────────────
|
||||||
|
logs: {
|
||||||
|
async list(params?: {
|
||||||
|
page?: number
|
||||||
|
page_size?: number
|
||||||
|
action?: string
|
||||||
|
}): Promise<PaginatedResponse<OperationLog>> {
|
||||||
|
const qs = buildQueryString(params)
|
||||||
|
return request<PaginatedResponse<OperationLog>>('GET', `/logs/operations${qs}`)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── 仪表盘 ────────────────────────────────────────────
|
||||||
|
stats: {
|
||||||
|
async dashboard(): Promise<DashboardStats> {
|
||||||
|
return request<DashboardStats>('GET', '/stats/dashboard')
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── 提示词管理 ────────────────────────────────────────
|
||||||
|
prompts: {
|
||||||
|
async list(params?: {
|
||||||
|
category?: string
|
||||||
|
source?: string
|
||||||
|
status?: string
|
||||||
|
page?: number
|
||||||
|
page_size?: number
|
||||||
|
}): Promise<PaginatedResponse<PromptTemplate>> {
|
||||||
|
const qs = buildQueryString(params)
|
||||||
|
return request<PaginatedResponse<PromptTemplate>>('GET', `/prompts${qs}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async get(name: string): Promise<PromptTemplate> {
|
||||||
|
return request<PromptTemplate>('GET', `/prompts/${encodeURIComponent(name)}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async create(data: {
|
||||||
|
name: string
|
||||||
|
category: string
|
||||||
|
description?: string
|
||||||
|
source?: string
|
||||||
|
system_prompt: string
|
||||||
|
user_prompt_template?: string
|
||||||
|
variables?: unknown[]
|
||||||
|
min_app_version?: string
|
||||||
|
}): Promise<PromptTemplate> {
|
||||||
|
return request<PromptTemplate>('POST', '/prompts', data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async update(name: string, data: {
|
||||||
|
description?: string
|
||||||
|
status?: string
|
||||||
|
}): Promise<PromptTemplate> {
|
||||||
|
return request<PromptTemplate>('PUT', `/prompts/${encodeURIComponent(name)}`, data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async archive(name: string): Promise<PromptTemplate> {
|
||||||
|
return request<PromptTemplate>('DELETE', `/prompts/${encodeURIComponent(name)}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async listVersions(name: string): Promise<PromptVersion[]> {
|
||||||
|
return request<PromptVersion[]>('GET', `/prompts/${encodeURIComponent(name)}/versions`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async createVersion(name: string, data: {
|
||||||
|
system_prompt: string
|
||||||
|
user_prompt_template?: string
|
||||||
|
variables?: unknown[]
|
||||||
|
changelog?: string
|
||||||
|
min_app_version?: string
|
||||||
|
}): Promise<PromptVersion> {
|
||||||
|
return request<PromptVersion>('POST', `/prompts/${encodeURIComponent(name)}/versions`, data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async rollback(name: string, version: number): Promise<PromptTemplate> {
|
||||||
|
return request<PromptTemplate>('POST', `/prompts/${encodeURIComponent(name)}/rollback/${version}`)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── Agent 配置模板 ──────────────────────────────────
|
||||||
|
agentTemplates: {
|
||||||
|
async list(params?: {
|
||||||
|
category?: string
|
||||||
|
source?: string
|
||||||
|
visibility?: string
|
||||||
|
status?: string
|
||||||
|
page?: number
|
||||||
|
page_size?: number
|
||||||
|
}): Promise<PaginatedResponse<AgentTemplate>> {
|
||||||
|
const qs = buildQueryString(params)
|
||||||
|
return request<PaginatedResponse<AgentTemplate>>('GET', `/agent-templates${qs}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async get(id: string): Promise<AgentTemplate> {
|
||||||
|
return request<AgentTemplate>('GET', `/agent-templates/${id}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
async create(data: {
|
||||||
|
name: string
|
||||||
|
description?: string
|
||||||
|
category?: string
|
||||||
|
source?: string
|
||||||
|
model?: string
|
||||||
|
system_prompt?: string
|
||||||
|
tools?: string[]
|
||||||
|
capabilities?: string[]
|
||||||
|
temperature?: number
|
||||||
|
max_tokens?: number
|
||||||
|
visibility?: string
|
||||||
|
}): Promise<AgentTemplate> {
|
||||||
|
return request<AgentTemplate>('POST', '/agent-templates', data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async update(id: string, data: {
|
||||||
|
description?: string
|
||||||
|
model?: string
|
||||||
|
system_prompt?: string
|
||||||
|
tools?: string[]
|
||||||
|
capabilities?: string[]
|
||||||
|
temperature?: number
|
||||||
|
max_tokens?: number
|
||||||
|
visibility?: string
|
||||||
|
status?: string
|
||||||
|
}): Promise<AgentTemplate> {
|
||||||
|
return request<AgentTemplate>('POST', `/agent-templates/${id}`, data)
|
||||||
|
},
|
||||||
|
|
||||||
|
async archive(id: string): Promise<AgentTemplate> {
|
||||||
|
return request<AgentTemplate>('DELETE', `/agent-templates/${id}`)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── 遥测统计 ──────────────────────────────────────────
|
||||||
|
telemetry: {
|
||||||
|
/** 按模型聚合用量统计 */
|
||||||
|
async modelStats(params?: {
|
||||||
|
from?: string
|
||||||
|
to?: string
|
||||||
|
model_id?: string
|
||||||
|
connection_mode?: string
|
||||||
|
}): Promise<ModelUsageStat[]> {
|
||||||
|
const qs = buildQueryString(params)
|
||||||
|
return request<ModelUsageStat[]>('GET', `/telemetry/stats${qs}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
/** 按天聚合用量统计 */
|
||||||
|
async dailyStats(params?: {
|
||||||
|
days?: number
|
||||||
|
}): Promise<DailyUsageStat[]> {
|
||||||
|
const qs = buildQueryString(params)
|
||||||
|
return request<DailyUsageStat[]>('GET', `/telemetry/daily${qs}`)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 工具函数 ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
function buildQueryString(params?: Record<string, unknown>): string {
|
||||||
|
if (!params) return ''
|
||||||
|
const entries = Object.entries(params).filter(
|
||||||
|
([, v]) => v !== undefined && v !== null && v !== '',
|
||||||
|
)
|
||||||
|
if (entries.length === 0) return ''
|
||||||
|
const qs = entries
|
||||||
|
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
|
||||||
|
.join('&')
|
||||||
|
return `?${qs}`
|
||||||
|
}
|
||||||
13
admin/src/lib/api-error.ts
Normal file
13
admin/src/lib/api-error.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
// ============================================================
|
||||||
|
// API Error 类 — 与 swr-fetcher 共享
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
export class ApiRequestError extends Error {
|
||||||
|
constructor(
|
||||||
|
public status: number,
|
||||||
|
public body: { error?: string; message?: string },
|
||||||
|
) {
|
||||||
|
super(body.message || `Request failed with status ${status}`)
|
||||||
|
this.name = 'ApiRequestError'
|
||||||
|
}
|
||||||
|
}
|
||||||
52
admin/src/lib/auth.ts
Normal file
52
admin/src/lib/auth.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
// ============================================================
|
||||||
|
// ZCLAW SaaS Admin — JWT Token 管理
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import type { AccountPublic } from './types'
|
||||||
|
|
||||||
|
const TOKEN_KEY = 'zclaw_admin_token'
|
||||||
|
const ACCOUNT_KEY = 'zclaw_admin_account'
|
||||||
|
|
||||||
|
/** 保存登录凭证 */
|
||||||
|
export function login(token: string, account: AccountPublic): void {
|
||||||
|
if (typeof window === 'undefined') return
|
||||||
|
localStorage.setItem(TOKEN_KEY, token)
|
||||||
|
localStorage.setItem(ACCOUNT_KEY, JSON.stringify(account))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 清除登录凭证 */
|
||||||
|
export function logout(): void {
|
||||||
|
if (typeof window === 'undefined') return
|
||||||
|
localStorage.removeItem(TOKEN_KEY)
|
||||||
|
localStorage.removeItem(ACCOUNT_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 清除认证状态(用于 Token 验证失败时) */
|
||||||
|
export function clearAuth(): void {
|
||||||
|
if (typeof window === 'undefined') return
|
||||||
|
localStorage.removeItem(TOKEN_KEY)
|
||||||
|
localStorage.removeItem(ACCOUNT_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 获取 JWT token */
|
||||||
|
export function getToken(): string | null {
|
||||||
|
if (typeof window === 'undefined') return null
|
||||||
|
return localStorage.getItem(TOKEN_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 获取当前登录用户信息 */
|
||||||
|
export function getAccount(): AccountPublic | null {
|
||||||
|
if (typeof window === 'undefined') return null
|
||||||
|
const raw = localStorage.getItem(ACCOUNT_KEY)
|
||||||
|
if (!raw) return null
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw) as AccountPublic
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 是否已认证 */
|
||||||
|
export function isAuthenticated(): boolean {
|
||||||
|
return !!getToken()
|
||||||
|
}
|
||||||
75
admin/src/lib/swr-fetcher.ts
Normal file
75
admin/src/lib/swr-fetcher.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
// ============================================================
|
||||||
|
// SWR fetcher — 将 SWR key 映射到 api-client 调用
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { api } from './api-client'
|
||||||
|
import { ApiRequestError } from './api-client'
|
||||||
|
|
||||||
|
type ApiMethod = typeof api
|
||||||
|
|
||||||
|
/** SWR fetcher: key 可以是字符串或 [method-path, params] 元组 */
|
||||||
|
type SwrKey =
|
||||||
|
| string
|
||||||
|
| [string, ...unknown[]]
|
||||||
|
|
||||||
|
/** SWR fetcher 支持 AbortSignal 传递 */
|
||||||
|
type SwrFetcherArgs = { signal?: AbortSignal } | null
|
||||||
|
|
||||||
|
async function resolveApiCall(key: SwrKey, args: SwrFetcherArgs): Promise<unknown> {
|
||||||
|
if (typeof key === 'string') {
|
||||||
|
// 简单字符串 key,直接 fetch
|
||||||
|
return fetchGeneric(key, args?.signal)
|
||||||
|
}
|
||||||
|
|
||||||
|
const [path, ...rest] = key
|
||||||
|
return callByPath(path, rest, args?.signal)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchGeneric(path: string, signal?: AbortSignal): Promise<unknown> {
|
||||||
|
const res = await fetch(path, {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
signal,
|
||||||
|
})
|
||||||
|
if (!res.ok) {
|
||||||
|
const body = await res.json().catch(() => ({ error: 'unknown', message: `请求失败 (${res.status})` }))
|
||||||
|
throw new ApiRequestError(res.status, body)
|
||||||
|
}
|
||||||
|
if (res.status === 204) return null
|
||||||
|
return res.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 根据 path 调用对应的 api 方法 */
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
async function callByPath(path: string, callArgs: unknown[], signal?: AbortSignal): Promise<unknown> {
|
||||||
|
const parts = path.split('.')
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
let target: any = api
|
||||||
|
for (const part of parts) {
|
||||||
|
target = target[part]
|
||||||
|
if (!target) throw new Error(`API method not found: ${path}`)
|
||||||
|
}
|
||||||
|
// Append signal as last argument if the target is the request function
|
||||||
|
// For api.xxx() calls that ultimately use request(), we pass signal through
|
||||||
|
// The simplest approach: pass signal as part of an options bag
|
||||||
|
return target(...callArgs, signal ? { signal } : undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SWR fetcher — 接受 SWR 自动传入的 AbortSignal
|
||||||
|
*
|
||||||
|
* 用法: useSWR(key, swrFetcher)
|
||||||
|
* SWR 会自动在组件卸载或 key 变化时 abort 请求
|
||||||
|
*/
|
||||||
|
export function swrFetcher<T = unknown>(key: SwrKey, args: SwrFetcherArgs): Promise<T> {
|
||||||
|
return resolveApiCall(key, args) as Promise<T>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 创建 SWR key helper — 类型安全 */
|
||||||
|
export function createKey<TMethod extends string>(
|
||||||
|
method: TMethod,
|
||||||
|
...args: unknown[]
|
||||||
|
): [TMethod, ...unknown[]] {
|
||||||
|
return [method, ...args]
|
||||||
|
}
|
||||||
38
admin/src/lib/swr-provider.tsx
Normal file
38
admin/src/lib/swr-provider.tsx
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { SWRConfig } from 'swr'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
|
/** 判断是否为请求被中断(页面导航等场景) */
|
||||||
|
function isAbortError(err: unknown): boolean {
|
||||||
|
if (err instanceof DOMException && err.name === 'AbortError') return true
|
||||||
|
if (err instanceof Error && err.message?.includes('aborted')) return true
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SWRProvider({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<SWRConfig
|
||||||
|
value={{
|
||||||
|
revalidateOnFocus: false,
|
||||||
|
dedupingInterval: 5000,
|
||||||
|
errorRetryCount: 2,
|
||||||
|
errorRetryInterval: 3000,
|
||||||
|
shouldRetryOnError: (err: unknown) => {
|
||||||
|
if (isAbortError(err)) return false
|
||||||
|
if (err && typeof err === 'object' && 'status' in err) {
|
||||||
|
const status = (err as { status: number }).status
|
||||||
|
return status !== 401 && status !== 403
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
},
|
||||||
|
onError: (err: unknown) => {
|
||||||
|
// 中断错误静默忽略,不展示给用户
|
||||||
|
if (isAbortError(err)) return
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</SWRConfig>
|
||||||
|
)
|
||||||
|
}
|
||||||
299
admin/src/lib/types.ts
Normal file
299
admin/src/lib/types.ts
Normal file
@@ -0,0 +1,299 @@
|
|||||||
|
// ============================================================
|
||||||
|
// ZCLAW SaaS Admin — 全局类型定义
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
/** 公共账号信息 */
|
||||||
|
export interface AccountPublic {
|
||||||
|
id: string
|
||||||
|
username: string
|
||||||
|
email: string
|
||||||
|
display_name: string
|
||||||
|
role: 'super_admin' | 'admin' | 'user'
|
||||||
|
status: 'active' | 'disabled' | 'suspended'
|
||||||
|
totp_enabled: boolean
|
||||||
|
last_login_at: string | null
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 登录请求 */
|
||||||
|
export interface LoginRequest {
|
||||||
|
username: string
|
||||||
|
password: string
|
||||||
|
totp_code?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 登录响应 */
|
||||||
|
export interface LoginResponse {
|
||||||
|
token: string
|
||||||
|
refresh_token: string
|
||||||
|
account: AccountPublic
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 注册请求 */
|
||||||
|
export interface RegisterRequest {
|
||||||
|
username: string
|
||||||
|
password: string
|
||||||
|
email: string
|
||||||
|
display_name?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 分页响应 */
|
||||||
|
export interface PaginatedResponse<T> {
|
||||||
|
items: T[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
page_size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 服务商 (Provider) */
|
||||||
|
export interface Provider {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
display_name: string
|
||||||
|
api_key?: string
|
||||||
|
base_url: string
|
||||||
|
api_protocol: string
|
||||||
|
enabled: boolean
|
||||||
|
rate_limit_rpm: number | null
|
||||||
|
rate_limit_tpm: number | null
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 模型 */
|
||||||
|
export interface Model {
|
||||||
|
id: string
|
||||||
|
provider_id: string
|
||||||
|
model_id: string
|
||||||
|
alias: string
|
||||||
|
context_window: number
|
||||||
|
max_output_tokens: number
|
||||||
|
supports_streaming: boolean
|
||||||
|
supports_vision: boolean
|
||||||
|
enabled: boolean
|
||||||
|
pricing_input: number
|
||||||
|
pricing_output: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** API 密钥信息 */
|
||||||
|
export interface TokenInfo {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
token_prefix: string
|
||||||
|
permissions: string[]
|
||||||
|
last_used_at?: string
|
||||||
|
expires_at?: string
|
||||||
|
created_at: string
|
||||||
|
token?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 创建 Token 请求 */
|
||||||
|
export interface CreateTokenRequest {
|
||||||
|
name: string
|
||||||
|
expires_days?: number
|
||||||
|
permissions: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 中转任务 */
|
||||||
|
export interface RelayTask {
|
||||||
|
id: string
|
||||||
|
account_id: string
|
||||||
|
provider_id: string
|
||||||
|
model_id: string
|
||||||
|
status: string
|
||||||
|
priority: number
|
||||||
|
attempt_count: number
|
||||||
|
max_attempts: number
|
||||||
|
input_tokens: number
|
||||||
|
output_tokens: number
|
||||||
|
error_message: string | null
|
||||||
|
queued_at: string
|
||||||
|
started_at: string | null
|
||||||
|
completed_at: string | null
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 用量记录 */
|
||||||
|
export interface UsageRecord {
|
||||||
|
day: string
|
||||||
|
count: number
|
||||||
|
input_tokens: number
|
||||||
|
output_tokens: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按模型用量 */
|
||||||
|
export interface UsageByModel {
|
||||||
|
model_id: string
|
||||||
|
count: number
|
||||||
|
input_tokens: number
|
||||||
|
output_tokens: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 系统配置项 */
|
||||||
|
export interface ConfigItem {
|
||||||
|
id: string
|
||||||
|
category: string
|
||||||
|
key_path: string
|
||||||
|
value_type: string
|
||||||
|
current_value: string | null
|
||||||
|
default_value: string | null
|
||||||
|
source: string
|
||||||
|
description: string | null
|
||||||
|
requires_restart: boolean
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 操作日志 */
|
||||||
|
export interface OperationLog {
|
||||||
|
id: number
|
||||||
|
account_id: string | null
|
||||||
|
action: string
|
||||||
|
target_type: string | null
|
||||||
|
target_id: string | null
|
||||||
|
details: Record<string, unknown> | null
|
||||||
|
ip_address: string | null
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 仪表盘统计 */
|
||||||
|
export interface DashboardStats {
|
||||||
|
total_accounts: number
|
||||||
|
active_accounts: number
|
||||||
|
tasks_today: number
|
||||||
|
active_providers: number
|
||||||
|
active_models: number
|
||||||
|
tokens_today_input: number
|
||||||
|
tokens_today_output: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** API 错误响应 */
|
||||||
|
export interface ApiError {
|
||||||
|
error: string
|
||||||
|
message: string
|
||||||
|
status?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 提示词模板 ────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** 提示词模板 */
|
||||||
|
export interface PromptTemplate {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
category: string
|
||||||
|
description?: string
|
||||||
|
source: 'builtin' | 'custom'
|
||||||
|
current_version: number
|
||||||
|
status: 'active' | 'deprecated' | 'archived'
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 提示词版本 */
|
||||||
|
export interface PromptVersion {
|
||||||
|
id: string
|
||||||
|
template_id: string
|
||||||
|
version: number
|
||||||
|
system_prompt: string
|
||||||
|
user_prompt_template?: string
|
||||||
|
variables: PromptVariable[]
|
||||||
|
changelog?: string
|
||||||
|
min_app_version?: string
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 提示词变量定义 */
|
||||||
|
export interface PromptVariable {
|
||||||
|
name: string
|
||||||
|
type: 'string' | 'number' | 'select' | 'boolean'
|
||||||
|
default_value?: string
|
||||||
|
description?: string
|
||||||
|
required?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** OTA 更新检查请求 */
|
||||||
|
export interface PromptCheckRequest {
|
||||||
|
device_id: string
|
||||||
|
versions: Record<string, number>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** OTA 更新响应 */
|
||||||
|
export interface PromptCheckResponse {
|
||||||
|
updates: PromptUpdatePayload[]
|
||||||
|
server_time: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 单个更新载荷 */
|
||||||
|
export interface PromptUpdatePayload {
|
||||||
|
name: string
|
||||||
|
version: number
|
||||||
|
system_prompt: string
|
||||||
|
user_prompt_template?: string
|
||||||
|
variables: PromptVariable[]
|
||||||
|
source: string
|
||||||
|
min_app_version?: string
|
||||||
|
changelog?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Agent 配置模板 ────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Agent 模板 */
|
||||||
|
export interface AgentTemplate {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
description?: string
|
||||||
|
category: string
|
||||||
|
source: 'builtin' | 'custom'
|
||||||
|
model?: string
|
||||||
|
system_prompt?: string
|
||||||
|
tools: string[]
|
||||||
|
capabilities: string[]
|
||||||
|
temperature?: number
|
||||||
|
max_tokens?: number
|
||||||
|
visibility: 'public' | 'team' | 'private'
|
||||||
|
status: 'active' | 'archived'
|
||||||
|
current_version: number
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Provider Key Pool ─────────────────────────────────────
|
||||||
|
|
||||||
|
/** Provider Key */
|
||||||
|
export interface ProviderKey {
|
||||||
|
id: string
|
||||||
|
provider_id: string
|
||||||
|
key_label: string
|
||||||
|
priority: number
|
||||||
|
max_rpm?: number
|
||||||
|
max_tpm?: number
|
||||||
|
quota_reset_interval?: string
|
||||||
|
is_active: boolean
|
||||||
|
last_429_at?: string
|
||||||
|
cooldown_until?: string
|
||||||
|
total_requests: number
|
||||||
|
total_tokens: number
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 遥测统计 ────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** 按模型聚合的用量统计 */
|
||||||
|
export interface ModelUsageStat {
|
||||||
|
model_id: string
|
||||||
|
request_count: number
|
||||||
|
input_tokens: number
|
||||||
|
output_tokens: number
|
||||||
|
avg_latency_ms: number | null
|
||||||
|
success_rate: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按天的用量统计 */
|
||||||
|
export interface DailyUsageStat {
|
||||||
|
day: string
|
||||||
|
request_count: number
|
||||||
|
input_tokens: number
|
||||||
|
output_tokens: number
|
||||||
|
unique_devices: number
|
||||||
|
}
|
||||||
45
admin/src/lib/utils.ts
Normal file
45
admin/src/lib/utils.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { type ClassValue, clsx } from 'clsx'
|
||||||
|
import { twMerge } from 'tailwind-merge'
|
||||||
|
|
||||||
|
export function cn(...inputs: ClassValue[]) {
|
||||||
|
return twMerge(clsx(inputs))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatDate(date: string | Date): string {
|
||||||
|
const d = new Date(date)
|
||||||
|
return d.toLocaleString('zh-CN', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
second: '2-digit',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatNumber(n: number): string {
|
||||||
|
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
|
||||||
|
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`
|
||||||
|
return n.toLocaleString()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function maskApiKey(key?: string): string {
|
||||||
|
if (!key) return '-'
|
||||||
|
if (key.length <= 8) return '****'
|
||||||
|
return `${key.slice(0, 4)}${'*'.repeat(key.length - 8)}${key.slice(-4)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sleep(ms: number): Promise<void> {
|
||||||
|
return new Promise(resolve => setTimeout(resolve, ms))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从 SWR error 中提取用户可见消息,过滤 abort 错误 */
|
||||||
|
export function getSwrErrorMessage(err: unknown): string | undefined {
|
||||||
|
if (!err) return undefined
|
||||||
|
if (err instanceof DOMException && err.name === 'AbortError') return undefined
|
||||||
|
if (err instanceof Error) {
|
||||||
|
if (err.name === 'AbortError' || err.message?.includes('aborted')) return undefined
|
||||||
|
return err.message
|
||||||
|
}
|
||||||
|
return String(err)
|
||||||
|
}
|
||||||
62
admin/tailwind.config.ts
Normal file
62
admin/tailwind.config.ts
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import type { Config } from 'tailwindcss'
|
||||||
|
|
||||||
|
const config: Config = {
|
||||||
|
darkMode: 'class',
|
||||||
|
content: [
|
||||||
|
'./src/pages/**/*.{js,ts,jsx,tsx,mdx}',
|
||||||
|
'./src/components/**/*.{js,ts,jsx,tsx,mdx}',
|
||||||
|
'./src/app/**/*.{js,ts,jsx,tsx,mdx}',
|
||||||
|
],
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
background: '#020617',
|
||||||
|
foreground: '#F8FAFC',
|
||||||
|
card: {
|
||||||
|
DEFAULT: '#0F172A',
|
||||||
|
foreground: '#F8FAFC',
|
||||||
|
},
|
||||||
|
primary: {
|
||||||
|
DEFAULT: '#22C55E',
|
||||||
|
foreground: '#020617',
|
||||||
|
hover: '#16A34A',
|
||||||
|
},
|
||||||
|
muted: {
|
||||||
|
DEFAULT: '#1E293B',
|
||||||
|
foreground: '#94A3B8',
|
||||||
|
},
|
||||||
|
accent: {
|
||||||
|
DEFAULT: '#334155',
|
||||||
|
foreground: '#F8FAFC',
|
||||||
|
},
|
||||||
|
destructive: {
|
||||||
|
DEFAULT: '#EF4444',
|
||||||
|
foreground: '#F8FAFC',
|
||||||
|
},
|
||||||
|
border: '#1E293B',
|
||||||
|
input: '#1E293B',
|
||||||
|
ring: '#22C55E',
|
||||||
|
},
|
||||||
|
fontFamily: {
|
||||||
|
sans: ['Inter', 'system-ui', '-apple-system', 'sans-serif'],
|
||||||
|
mono: ['JetBrains Mono', 'Fira Code', 'monospace'],
|
||||||
|
},
|
||||||
|
keyframes: {
|
||||||
|
'fade-in': {
|
||||||
|
'0%': { opacity: '0', transform: 'translateY(4px)' },
|
||||||
|
'100%': { opacity: '1', transform: 'translateY(0)' },
|
||||||
|
},
|
||||||
|
'slide-in': {
|
||||||
|
'0%': { opacity: '0', transform: 'translateX(-8px)' },
|
||||||
|
'100%': { opacity: '1', transform: 'translateX(0)' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
animation: {
|
||||||
|
'fade-in': 'fade-in 0.2s ease-out',
|
||||||
|
'slide-in': 'slide-in 0.2s ease-out',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
}
|
||||||
|
export default config
|
||||||
21
admin/tsconfig.json
Normal file
21
admin/tsconfig.json
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "es2017",
|
||||||
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
|
"allowJs": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strict": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"jsx": "preserve",
|
||||||
|
"incremental": true,
|
||||||
|
"plugins": [{ "name": "next" }],
|
||||||
|
"paths": { "@/*": ["./src/*"] }
|
||||||
|
},
|
||||||
|
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
|
}
|
||||||
33
config/saas-development.toml
Normal file
33
config/saas-development.toml
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
# ZCLAW SaaS 开发环境配置
|
||||||
|
# 通过 ZCLAW_ENV=development 或默认使用此配置
|
||||||
|
|
||||||
|
[server]
|
||||||
|
host = "0.0.0.0"
|
||||||
|
port = 8080
|
||||||
|
cors_origins = [] # 空 = 开发模式允许所有来源
|
||||||
|
|
||||||
|
[database]
|
||||||
|
url = "postgres://postgres:123123@localhost:5432/zclaw"
|
||||||
|
|
||||||
|
[auth]
|
||||||
|
jwt_expiration_hours = 24
|
||||||
|
totp_issuer = "ZCLAW SaaS (dev)"
|
||||||
|
refresh_token_hours = 168
|
||||||
|
|
||||||
|
[relay]
|
||||||
|
max_queue_size = 1000
|
||||||
|
max_concurrent_per_provider = 5
|
||||||
|
batch_window_ms = 50
|
||||||
|
retry_delay_ms = 1000
|
||||||
|
max_attempts = 3
|
||||||
|
|
||||||
|
[rate_limit]
|
||||||
|
requests_per_minute = 120
|
||||||
|
burst = 20
|
||||||
|
|
||||||
|
[scheduler]
|
||||||
|
jobs = [
|
||||||
|
{ name = "cleanup_rate_limit", interval = "5m", task = "cleanup_rate_limit", run_on_start = false },
|
||||||
|
{ name = "cleanup_refresh_tokens", interval = "1h", task = "cleanup_refresh_tokens", run_on_start = false },
|
||||||
|
{ name = "cleanup_devices", interval = "24h", task = "cleanup_devices", run_on_start = false },
|
||||||
|
]
|
||||||
35
config/saas-production.toml
Normal file
35
config/saas-production.toml
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
# ZCLAW SaaS 生产环境配置
|
||||||
|
# 通过 ZCLAW_ENV=production 使用此配置
|
||||||
|
|
||||||
|
[server]
|
||||||
|
host = "0.0.0.0"
|
||||||
|
port = 8080
|
||||||
|
# 生产环境必须配置 CORS 白名单
|
||||||
|
cors_origins = ["https://admin.zclaw.ai", "https://zclaw.ai"]
|
||||||
|
|
||||||
|
[database]
|
||||||
|
# 生产环境通过 ZCLAW_DATABASE_URL 环境变量覆盖,此处为占位
|
||||||
|
url = "postgres://zclaw:CHANGE_ME@db:5432/zclaw"
|
||||||
|
|
||||||
|
[auth]
|
||||||
|
jwt_expiration_hours = 12
|
||||||
|
totp_issuer = "ZCLAW SaaS"
|
||||||
|
refresh_token_hours = 168
|
||||||
|
|
||||||
|
[relay]
|
||||||
|
max_queue_size = 5000
|
||||||
|
max_concurrent_per_provider = 10
|
||||||
|
batch_window_ms = 50
|
||||||
|
retry_delay_ms = 2000
|
||||||
|
max_attempts = 3
|
||||||
|
|
||||||
|
[rate_limit]
|
||||||
|
requests_per_minute = 60
|
||||||
|
burst = 10
|
||||||
|
|
||||||
|
[scheduler]
|
||||||
|
jobs = [
|
||||||
|
{ name = "cleanup_rate_limit", interval = "5m", task = "cleanup_rate_limit", run_on_start = false },
|
||||||
|
{ name = "cleanup_refresh_tokens", interval = "1h", task = "cleanup_refresh_tokens", run_on_start = false },
|
||||||
|
{ name = "cleanup_devices", interval = "24h", task = "cleanup_devices", run_on_start = true },
|
||||||
|
]
|
||||||
31
config/saas-test.toml
Normal file
31
config/saas-test.toml
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
# ZCLAW SaaS 测试环境配置
|
||||||
|
# 通过 ZCLAW_ENV=test 使用此配置
|
||||||
|
|
||||||
|
[server]
|
||||||
|
host = "127.0.0.1"
|
||||||
|
port = 8090
|
||||||
|
cors_origins = []
|
||||||
|
|
||||||
|
[database]
|
||||||
|
# 测试环境使用独立数据库
|
||||||
|
url = "postgres://postgres:123123@localhost:5432/zclaw_test"
|
||||||
|
|
||||||
|
[auth]
|
||||||
|
jwt_expiration_hours = 1
|
||||||
|
totp_issuer = "ZCLAW SaaS (test)"
|
||||||
|
refresh_token_hours = 24
|
||||||
|
|
||||||
|
[relay]
|
||||||
|
max_queue_size = 100
|
||||||
|
max_concurrent_per_provider = 2
|
||||||
|
batch_window_ms = 10
|
||||||
|
retry_delay_ms = 100
|
||||||
|
max_attempts = 2
|
||||||
|
|
||||||
|
[rate_limit]
|
||||||
|
requests_per_minute = 200
|
||||||
|
burst = 50
|
||||||
|
|
||||||
|
[scheduler]
|
||||||
|
# 测试环境不启动定时任务
|
||||||
|
jobs = []
|
||||||
@@ -289,6 +289,44 @@ impl sqlx::FromRow<'_, SqliteRow> for MemoryRow {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Private helper methods on SqliteStorage (NOT in impl VikingStorage block)
|
||||||
|
impl SqliteStorage {
|
||||||
|
/// Fetch memories by scope with importance-based ordering.
|
||||||
|
/// Used internally by find() for scope-based queries.
|
||||||
|
pub(crate) async fn fetch_by_scope_priv(&self, scope: Option<&str>, limit: usize) -> Result<Vec<MemoryRow>> {
|
||||||
|
let rows = if let Some(scope) = scope {
|
||||||
|
sqlx::query_as::<_, MemoryRow>(
|
||||||
|
r#"
|
||||||
|
SELECT uri, memory_type, content, keywords, importance, access_count, created_at, last_accessed, overview, abstract_summary
|
||||||
|
FROM memories
|
||||||
|
WHERE uri LIKE ?
|
||||||
|
ORDER BY importance DESC, access_count DESC
|
||||||
|
LIMIT ?
|
||||||
|
"#
|
||||||
|
)
|
||||||
|
.bind(format!("{}%", scope))
|
||||||
|
.bind(limit as i64)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| ZclawError::StorageError(format!("Failed to fetch by scope: {}", e)))?
|
||||||
|
} else {
|
||||||
|
sqlx::query_as::<_, MemoryRow>(
|
||||||
|
r#"
|
||||||
|
SELECT uri, memory_type, content, keywords, importance, access_count, created_at, last_accessed, overview, abstract_summary
|
||||||
|
FROM memories
|
||||||
|
ORDER BY importance DESC
|
||||||
|
LIMIT ?
|
||||||
|
"#
|
||||||
|
)
|
||||||
|
.bind(limit as i64)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| ZclawError::StorageError(format!("Failed to fetch by scope: {}", e)))?
|
||||||
|
};
|
||||||
|
Ok(rows)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl VikingStorage for SqliteStorage {
|
impl VikingStorage for SqliteStorage {
|
||||||
async fn store(&self, entry: &MemoryEntry) -> Result<()> {
|
async fn store(&self, entry: &MemoryEntry) -> Result<()> {
|
||||||
@@ -374,22 +412,61 @@ impl VikingStorage for SqliteStorage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn find(&self, query: &str, options: FindOptions) -> Result<Vec<MemoryEntry>> {
|
async fn find(&self, query: &str, options: FindOptions) -> Result<Vec<MemoryEntry>> {
|
||||||
// Get all matching entries
|
let limit = options.limit.unwrap_or(50).max(20); // Fetch more candidates for reranking
|
||||||
let rows = if let Some(ref scope) = options.scope {
|
|
||||||
sqlx::query_as::<_, MemoryRow>(
|
// Strategy: use FTS5 for initial filtering when query is non-empty,
|
||||||
"SELECT uri, memory_type, content, keywords, importance, access_count, created_at, last_accessed, overview, abstract_summary FROM memories WHERE uri LIKE ?"
|
// then score candidates with TF-IDF / embedding for precise ranking.
|
||||||
)
|
// Fallback to scope-only scan when query is empty (e.g., "list all").
|
||||||
.bind(format!("{}%", scope))
|
let rows = if !query.is_empty() {
|
||||||
.fetch_all(&self.pool)
|
// FTS5-powered candidate retrieval (fast, index-based)
|
||||||
.await
|
let fts_candidates = if let Some(ref scope) = options.scope {
|
||||||
.map_err(|e| ZclawError::StorageError(format!("Failed to find memories: {}", e)))?
|
sqlx::query_as::<_, MemoryRow>(
|
||||||
|
r#"
|
||||||
|
SELECT m.uri, m.memory_type, m.content, m.keywords, m.importance,
|
||||||
|
m.access_count, m.created_at, m.last_accessed, m.overview, m.abstract_summary
|
||||||
|
FROM memories m
|
||||||
|
INNER JOIN memories_fts f ON m.uri = f.uri
|
||||||
|
WHERE f.memories_fts MATCH ?
|
||||||
|
AND m.uri LIKE ?
|
||||||
|
ORDER BY f.rank
|
||||||
|
LIMIT ?
|
||||||
|
"#
|
||||||
|
)
|
||||||
|
.bind(query)
|
||||||
|
.bind(format!("{}%", scope))
|
||||||
|
.bind(limit as i64)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await
|
||||||
|
} else {
|
||||||
|
sqlx::query_as::<_, MemoryRow>(
|
||||||
|
r#"
|
||||||
|
SELECT m.uri, m.memory_type, m.content, m.keywords, m.importance,
|
||||||
|
m.access_count, m.created_at, m.last_accessed, m.overview, m.abstract_summary
|
||||||
|
FROM memories m
|
||||||
|
INNER JOIN memories_fts f ON m.uri = f.uri
|
||||||
|
WHERE f.memories_fts MATCH ?
|
||||||
|
ORDER BY f.rank
|
||||||
|
LIMIT ?
|
||||||
|
"#
|
||||||
|
)
|
||||||
|
.bind(query)
|
||||||
|
.bind(limit as i64)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await
|
||||||
|
};
|
||||||
|
|
||||||
|
match fts_candidates {
|
||||||
|
Ok(rows) if !rows.is_empty() => rows,
|
||||||
|
Ok(_) | Err(_) => {
|
||||||
|
// FTS5 returned nothing or query syntax was invalid —
|
||||||
|
// fallback to scope-based scan (no full table scan unless no scope)
|
||||||
|
tracing::debug!("[SqliteStorage] FTS5 returned no results, falling back to scope scan");
|
||||||
|
self.fetch_by_scope_priv(options.scope.as_deref(), limit).await?
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
sqlx::query_as::<_, MemoryRow>(
|
// Empty query: scope-based scan only (no FTS5 needed)
|
||||||
"SELECT uri, memory_type, content, keywords, importance, access_count, created_at, last_accessed, overview, abstract_summary FROM memories"
|
self.fetch_by_scope_priv(options.scope.as_deref(), limit).await?
|
||||||
)
|
|
||||||
.fetch_all(&self.pool)
|
|
||||||
.await
|
|
||||||
.map_err(|e| ZclawError::StorageError(format!("Failed to find memories: {}", e)))?
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Convert to entries and compute semantic scores
|
// Convert to entries and compute semantic scores
|
||||||
@@ -464,16 +541,8 @@ impl VikingStorage for SqliteStorage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn find_by_prefix(&self, prefix: &str) -> Result<Vec<MemoryEntry>> {
|
async fn find_by_prefix(&self, prefix: &str) -> Result<Vec<MemoryEntry>> {
|
||||||
let rows = sqlx::query_as::<_, MemoryRow>(
|
let rows = self.fetch_by_scope_priv(Some(prefix), 100).await?;
|
||||||
"SELECT uri, memory_type, content, keywords, importance, access_count, created_at, last_accessed, overview, abstract_summary FROM memories WHERE uri LIKE ?"
|
|
||||||
)
|
|
||||||
.bind(format!("{}%", prefix))
|
|
||||||
.fetch_all(&self.pool)
|
|
||||||
.await
|
|
||||||
.map_err(|e| ZclawError::StorageError(format!("Failed to find by prefix: {}", e)))?;
|
|
||||||
|
|
||||||
let entries = rows.iter().map(|row| self.row_to_entry(row)).collect();
|
let entries = rows.iter().map(|row| self.row_to_entry(row)).collect();
|
||||||
|
|
||||||
Ok(entries)
|
Ok(entries)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -484,13 +553,13 @@ impl VikingStorage for SqliteStorage {
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| ZclawError::StorageError(format!("Failed to delete memory: {}", e)))?;
|
.map_err(|e| ZclawError::StorageError(format!("Failed to delete memory: {}", e)))?;
|
||||||
|
|
||||||
// Remove from FTS
|
// Remove from FTS index
|
||||||
let _ = sqlx::query("DELETE FROM memories_fts WHERE uri = ?")
|
let _ = sqlx::query("DELETE FROM memories_fts WHERE uri = ?")
|
||||||
.bind(uri)
|
.bind(uri)
|
||||||
.execute(&self.pool)
|
.execute(&self.pool)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
// Remove from scorer
|
// Remove from in-memory scorer
|
||||||
let mut scorer = self.scorer.write().await;
|
let mut scorer = self.scorer.write().await;
|
||||||
scorer.remove_entry(uri);
|
scorer.remove_entry(uri);
|
||||||
|
|
||||||
|
|||||||
@@ -54,6 +54,11 @@ pub struct LlmConfig {
|
|||||||
/// Temperature
|
/// Temperature
|
||||||
#[serde(default = "default_temperature")]
|
#[serde(default = "default_temperature")]
|
||||||
pub temperature: f32,
|
pub temperature: f32,
|
||||||
|
|
||||||
|
/// Context window size in tokens (default: 128000)
|
||||||
|
/// Used to calculate dynamic compaction threshold.
|
||||||
|
#[serde(default = "default_context_window")]
|
||||||
|
pub context_window: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LlmConfig {
|
impl LlmConfig {
|
||||||
@@ -66,6 +71,7 @@ impl LlmConfig {
|
|||||||
api_protocol: ApiProtocol::OpenAI,
|
api_protocol: ApiProtocol::OpenAI,
|
||||||
max_tokens: default_max_tokens(),
|
max_tokens: default_max_tokens(),
|
||||||
temperature: default_temperature(),
|
temperature: default_temperature(),
|
||||||
|
context_window: default_context_window(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,6 +146,10 @@ fn default_temperature() -> f32 {
|
|||||||
0.7
|
0.7
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn default_context_window() -> u32 {
|
||||||
|
128000
|
||||||
|
}
|
||||||
|
|
||||||
impl Default for KernelConfig {
|
impl Default for KernelConfig {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -151,6 +161,7 @@ impl Default for KernelConfig {
|
|||||||
api_protocol: ApiProtocol::OpenAI,
|
api_protocol: ApiProtocol::OpenAI,
|
||||||
max_tokens: default_max_tokens(),
|
max_tokens: default_max_tokens(),
|
||||||
temperature: default_temperature(),
|
temperature: default_temperature(),
|
||||||
|
context_window: default_context_window(),
|
||||||
},
|
},
|
||||||
skills_dir: default_skills_dir(),
|
skills_dir: default_skills_dir(),
|
||||||
}
|
}
|
||||||
@@ -345,6 +356,17 @@ impl KernelConfig {
|
|||||||
pub fn temperature(&self) -> f32 {
|
pub fn temperature(&self) -> f32 {
|
||||||
self.llm.temperature
|
self.llm.temperature
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get context window size in tokens
|
||||||
|
pub fn context_window(&self) -> u32 {
|
||||||
|
self.llm.context_window
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dynamic compaction threshold = context_window * 0.6
|
||||||
|
/// Leaves 40% headroom for system prompt + response tokens
|
||||||
|
pub fn compaction_threshold(&self) -> usize {
|
||||||
|
(self.llm.context_window as f64 * 0.6) as usize
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// === Preset configurations for common providers ===
|
// === Preset configurations for common providers ===
|
||||||
|
|||||||
@@ -3,7 +3,9 @@
|
|||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::sync::{broadcast, mpsc, Mutex};
|
use tokio::sync::{broadcast, mpsc, Mutex};
|
||||||
use zclaw_types::{AgentConfig, AgentId, AgentInfo, Event, Result};
|
use zclaw_types::{AgentConfig, AgentId, AgentInfo, Capability, Event, Result, HandRun, HandRunId, HandRunStatus, HandRunFilter, TriggerSource};
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
use zclaw_protocols::{A2aRouter, A2aAgentProfile, A2aCapability, A2aEnvelope, A2aMessageType, A2aRecipient};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
@@ -12,7 +14,7 @@ use crate::capabilities::CapabilityManager;
|
|||||||
use crate::events::EventBus;
|
use crate::events::EventBus;
|
||||||
use crate::config::KernelConfig;
|
use crate::config::KernelConfig;
|
||||||
use zclaw_memory::MemoryStore;
|
use zclaw_memory::MemoryStore;
|
||||||
use zclaw_runtime::{AgentLoop, LlmDriver, ToolRegistry, tool::SkillExecutor};
|
use zclaw_runtime::{AgentLoop, LlmDriver, ToolRegistry, tool::SkillExecutor, tool::builtin::PathValidator};
|
||||||
use zclaw_skills::SkillRegistry;
|
use zclaw_skills::SkillRegistry;
|
||||||
use zclaw_skills::LlmCompleter;
|
use zclaw_skills::LlmCompleter;
|
||||||
use zclaw_hands::{HandRegistry, HandContext, HandResult, hands::{BrowserHand, SlideshowHand, SpeechHand, QuizHand, WhiteboardHand, ResearcherHand, CollectorHand, ClipHand, TwitterHand, quiz::LlmQuizGenerator}};
|
use zclaw_hands::{HandRegistry, HandContext, HandResult, hands::{BrowserHand, SlideshowHand, SpeechHand, QuizHand, WhiteboardHand, ResearcherHand, CollectorHand, ClipHand, TwitterHand, quiz::LlmQuizGenerator}};
|
||||||
@@ -20,6 +22,8 @@ use zclaw_hands::{HandRegistry, HandContext, HandResult, hands::{BrowserHand, Sl
|
|||||||
/// Adapter that bridges `zclaw_runtime::LlmDriver` → `zclaw_skills::LlmCompleter`
|
/// Adapter that bridges `zclaw_runtime::LlmDriver` → `zclaw_skills::LlmCompleter`
|
||||||
struct LlmDriverAdapter {
|
struct LlmDriverAdapter {
|
||||||
driver: Arc<dyn LlmDriver>,
|
driver: Arc<dyn LlmDriver>,
|
||||||
|
max_tokens: u32,
|
||||||
|
temperature: f32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl zclaw_skills::LlmCompleter for LlmDriverAdapter {
|
impl zclaw_skills::LlmCompleter for LlmDriverAdapter {
|
||||||
@@ -32,8 +36,8 @@ impl zclaw_skills::LlmCompleter for LlmDriverAdapter {
|
|||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let request = zclaw_runtime::CompletionRequest {
|
let request = zclaw_runtime::CompletionRequest {
|
||||||
messages: vec![zclaw_types::Message::user(prompt)],
|
messages: vec![zclaw_types::Message::user(prompt)],
|
||||||
max_tokens: Some(4096),
|
max_tokens: Some(self.max_tokens),
|
||||||
temperature: Some(0.7),
|
temperature: Some(self.temperature),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
let response = driver.complete(request).await
|
let response = driver.complete(request).await
|
||||||
@@ -59,7 +63,7 @@ pub struct KernelSkillExecutor {
|
|||||||
|
|
||||||
impl KernelSkillExecutor {
|
impl KernelSkillExecutor {
|
||||||
pub fn new(skills: Arc<SkillRegistry>, driver: Arc<dyn LlmDriver>) -> Self {
|
pub fn new(skills: Arc<SkillRegistry>, driver: Arc<dyn LlmDriver>) -> Self {
|
||||||
let llm: Arc<dyn zclaw_skills::LlmCompleter> = Arc::new(LlmDriverAdapter { driver });
|
let llm: Arc<dyn zclaw_skills::LlmCompleter> = Arc::new(LlmDriverAdapter { driver, max_tokens: 4096, temperature: 0.7 });
|
||||||
Self { skills, llm }
|
Self { skills, llm }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -98,6 +102,14 @@ pub struct Kernel {
|
|||||||
hands: Arc<HandRegistry>,
|
hands: Arc<HandRegistry>,
|
||||||
trigger_manager: crate::trigger_manager::TriggerManager,
|
trigger_manager: crate::trigger_manager::TriggerManager,
|
||||||
pending_approvals: Arc<Mutex<Vec<ApprovalEntry>>>,
|
pending_approvals: Arc<Mutex<Vec<ApprovalEntry>>>,
|
||||||
|
/// Running hand runs that can be cancelled (run_id -> cancelled flag)
|
||||||
|
running_hand_runs: Arc<dashmap::DashMap<HandRunId, Arc<std::sync::atomic::AtomicBool>>>,
|
||||||
|
/// A2A router for inter-agent messaging (gated by multi-agent feature)
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
a2a_router: Arc<A2aRouter>,
|
||||||
|
/// Per-agent A2A inbox receivers
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
a2a_inboxes: Arc<dashmap::DashMap<AgentId, Arc<Mutex<mpsc::Receiver<A2aEnvelope>>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Kernel {
|
impl Kernel {
|
||||||
@@ -143,7 +155,11 @@ impl Kernel {
|
|||||||
|
|
||||||
// Create LLM completer for skill system (shared with skill_executor)
|
// Create LLM completer for skill system (shared with skill_executor)
|
||||||
let llm_completer: Arc<dyn zclaw_skills::LlmCompleter> =
|
let llm_completer: Arc<dyn zclaw_skills::LlmCompleter> =
|
||||||
Arc::new(LlmDriverAdapter { driver: driver.clone() });
|
Arc::new(LlmDriverAdapter {
|
||||||
|
driver: driver.clone(),
|
||||||
|
max_tokens: config.max_tokens(),
|
||||||
|
temperature: config.temperature(),
|
||||||
|
});
|
||||||
|
|
||||||
// Initialize trigger manager
|
// Initialize trigger manager
|
||||||
let trigger_manager = crate::trigger_manager::TriggerManager::new(hands.clone());
|
let trigger_manager = crate::trigger_manager::TriggerManager::new(hands.clone());
|
||||||
@@ -154,6 +170,13 @@ impl Kernel {
|
|||||||
registry.register(agent);
|
registry.register(agent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Initialize A2A router for multi-agent support
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
let a2a_router = {
|
||||||
|
let kernel_agent_id = AgentId::new();
|
||||||
|
Arc::new(A2aRouter::new(kernel_agent_id))
|
||||||
|
};
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
config,
|
config,
|
||||||
registry,
|
registry,
|
||||||
@@ -167,6 +190,11 @@ impl Kernel {
|
|||||||
hands,
|
hands,
|
||||||
trigger_manager,
|
trigger_manager,
|
||||||
pending_approvals: Arc::new(Mutex::new(Vec::new())),
|
pending_approvals: Arc::new(Mutex::new(Vec::new())),
|
||||||
|
running_hand_runs: Arc::new(dashmap::DashMap::new()),
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
a2a_router,
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
a2a_inboxes: Arc::new(dashmap::DashMap::new()),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,8 +322,17 @@ impl Kernel {
|
|||||||
self.memory.save_agent(&config).await?;
|
self.memory.save_agent(&config).await?;
|
||||||
|
|
||||||
// Register in registry
|
// Register in registry
|
||||||
|
let config_clone = config.clone();
|
||||||
self.registry.register(config);
|
self.registry.register(config);
|
||||||
|
|
||||||
|
// Register with A2A router for multi-agent messaging
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
{
|
||||||
|
let profile = Self::agent_config_to_a2a_profile(&config_clone);
|
||||||
|
let rx = self.a2a_router.register_agent(profile).await;
|
||||||
|
self.a2a_inboxes.insert(id, Arc::new(Mutex::new(rx)));
|
||||||
|
}
|
||||||
|
|
||||||
// Emit event
|
// Emit event
|
||||||
self.events.publish(Event::AgentSpawned {
|
self.events.publish(Event::AgentSpawned {
|
||||||
agent_id: id,
|
agent_id: id,
|
||||||
@@ -313,6 +350,13 @@ impl Kernel {
|
|||||||
// Remove from memory
|
// Remove from memory
|
||||||
self.memory.delete_agent(id).await?;
|
self.memory.delete_agent(id).await?;
|
||||||
|
|
||||||
|
// Unregister from A2A router
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
{
|
||||||
|
self.a2a_router.unregister_agent(id).await;
|
||||||
|
self.a2a_inboxes.remove(id);
|
||||||
|
}
|
||||||
|
|
||||||
// Emit event
|
// Emit event
|
||||||
self.events.publish(Event::AgentTerminated {
|
self.events.publish(Event::AgentTerminated {
|
||||||
agent_id: *id,
|
agent_id: *id,
|
||||||
@@ -346,7 +390,7 @@ impl Kernel {
|
|||||||
|
|
||||||
// Create agent loop with model configuration
|
// Create agent loop with model configuration
|
||||||
let tools = self.create_tool_registry();
|
let tools = self.create_tool_registry();
|
||||||
let loop_runner = AgentLoop::new(
|
let mut loop_runner = AgentLoop::new(
|
||||||
*agent_id,
|
*agent_id,
|
||||||
self.driver.clone(),
|
self.driver.clone(),
|
||||||
tools,
|
tools,
|
||||||
@@ -356,7 +400,22 @@ impl Kernel {
|
|||||||
.with_skill_executor(self.skill_executor.clone())
|
.with_skill_executor(self.skill_executor.clone())
|
||||||
.with_max_tokens(agent_config.max_tokens.unwrap_or_else(|| self.config.max_tokens()))
|
.with_max_tokens(agent_config.max_tokens.unwrap_or_else(|| self.config.max_tokens()))
|
||||||
.with_temperature(agent_config.temperature.unwrap_or_else(|| self.config.temperature()))
|
.with_temperature(agent_config.temperature.unwrap_or_else(|| self.config.temperature()))
|
||||||
.with_compaction_threshold(15_000); // Compact when context exceeds ~15k tokens
|
.with_compaction_threshold(
|
||||||
|
agent_config.compaction_threshold
|
||||||
|
.map(|t| t as usize)
|
||||||
|
.unwrap_or_else(|| self.config.compaction_threshold()),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Set path validator from agent's workspace directory (if configured)
|
||||||
|
if let Some(ref workspace) = agent_config.workspace {
|
||||||
|
let path_validator = PathValidator::new().with_workspace(workspace.clone());
|
||||||
|
tracing::info!(
|
||||||
|
"[Kernel] Setting path_validator with workspace: {} for agent {}",
|
||||||
|
workspace.display(),
|
||||||
|
agent_id
|
||||||
|
);
|
||||||
|
loop_runner = loop_runner.with_path_validator(path_validator);
|
||||||
|
}
|
||||||
|
|
||||||
// Build system prompt with skill information injected
|
// Build system prompt with skill information injected
|
||||||
let system_prompt = self.build_system_prompt_with_skills(agent_config.system_prompt.as_ref()).await;
|
let system_prompt = self.build_system_prompt_with_skills(agent_config.system_prompt.as_ref()).await;
|
||||||
@@ -378,21 +437,35 @@ impl Kernel {
|
|||||||
agent_id: &AgentId,
|
agent_id: &AgentId,
|
||||||
message: String,
|
message: String,
|
||||||
) -> Result<mpsc::Receiver<zclaw_runtime::LoopEvent>> {
|
) -> Result<mpsc::Receiver<zclaw_runtime::LoopEvent>> {
|
||||||
self.send_message_stream_with_prompt(agent_id, message, None).await
|
self.send_message_stream_with_prompt(agent_id, message, None, None).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send a message with streaming and optional external system prompt
|
/// Send a message with streaming, optional system prompt, and optional session reuse
|
||||||
pub async fn send_message_stream_with_prompt(
|
pub async fn send_message_stream_with_prompt(
|
||||||
&self,
|
&self,
|
||||||
agent_id: &AgentId,
|
agent_id: &AgentId,
|
||||||
message: String,
|
message: String,
|
||||||
system_prompt_override: Option<String>,
|
system_prompt_override: Option<String>,
|
||||||
|
session_id_override: Option<zclaw_types::SessionId>,
|
||||||
) -> Result<mpsc::Receiver<zclaw_runtime::LoopEvent>> {
|
) -> Result<mpsc::Receiver<zclaw_runtime::LoopEvent>> {
|
||||||
let agent_config = self.registry.get(agent_id)
|
let agent_config = self.registry.get(agent_id)
|
||||||
.ok_or_else(|| zclaw_types::ZclawError::NotFound(format!("Agent not found: {}", agent_id)))?;
|
.ok_or_else(|| zclaw_types::ZclawError::NotFound(format!("Agent not found: {}", agent_id)))?;
|
||||||
|
|
||||||
// Create session
|
// Reuse existing session or create new one
|
||||||
let session_id = self.memory.create_session(agent_id).await?;
|
let session_id = match session_id_override {
|
||||||
|
Some(id) => {
|
||||||
|
// Verify the session exists; if not, create a new one
|
||||||
|
let existing = self.memory.get_messages(&id).await;
|
||||||
|
match existing {
|
||||||
|
Ok(msgs) if !msgs.is_empty() => id,
|
||||||
|
_ => {
|
||||||
|
tracing::debug!("Session {} not found or empty, creating new session", id);
|
||||||
|
self.memory.create_session(agent_id).await?
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => self.memory.create_session(agent_id).await?,
|
||||||
|
};
|
||||||
|
|
||||||
// Always use Kernel's current model configuration
|
// Always use Kernel's current model configuration
|
||||||
// This ensures user's "模型与 API" settings are respected
|
// This ensures user's "模型与 API" settings are respected
|
||||||
@@ -400,7 +473,7 @@ impl Kernel {
|
|||||||
|
|
||||||
// Create agent loop with model configuration
|
// Create agent loop with model configuration
|
||||||
let tools = self.create_tool_registry();
|
let tools = self.create_tool_registry();
|
||||||
let loop_runner = AgentLoop::new(
|
let mut loop_runner = AgentLoop::new(
|
||||||
*agent_id,
|
*agent_id,
|
||||||
self.driver.clone(),
|
self.driver.clone(),
|
||||||
tools,
|
tools,
|
||||||
@@ -410,7 +483,23 @@ impl Kernel {
|
|||||||
.with_skill_executor(self.skill_executor.clone())
|
.with_skill_executor(self.skill_executor.clone())
|
||||||
.with_max_tokens(agent_config.max_tokens.unwrap_or_else(|| self.config.max_tokens()))
|
.with_max_tokens(agent_config.max_tokens.unwrap_or_else(|| self.config.max_tokens()))
|
||||||
.with_temperature(agent_config.temperature.unwrap_or_else(|| self.config.temperature()))
|
.with_temperature(agent_config.temperature.unwrap_or_else(|| self.config.temperature()))
|
||||||
.with_compaction_threshold(15_000); // Compact when context exceeds ~15k tokens
|
.with_compaction_threshold(
|
||||||
|
agent_config.compaction_threshold
|
||||||
|
.map(|t| t as usize)
|
||||||
|
.unwrap_or_else(|| self.config.compaction_threshold()),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Set path validator from agent's workspace directory (if configured)
|
||||||
|
// This enables file_read / file_write tools to access the workspace
|
||||||
|
if let Some(ref workspace) = agent_config.workspace {
|
||||||
|
let path_validator = PathValidator::new().with_workspace(workspace.clone());
|
||||||
|
tracing::info!(
|
||||||
|
"[Kernel] Setting path_validator with workspace: {} for agent {}",
|
||||||
|
workspace.display(),
|
||||||
|
agent_id
|
||||||
|
);
|
||||||
|
loop_runner = loop_runner.with_path_validator(path_validator);
|
||||||
|
}
|
||||||
|
|
||||||
// Use external prompt if provided, otherwise build default
|
// Use external prompt if provided, otherwise build default
|
||||||
let system_prompt = match system_prompt_override {
|
let system_prompt = match system_prompt_override {
|
||||||
@@ -489,15 +578,194 @@ impl Kernel {
|
|||||||
self.hands.list().await
|
self.hands.list().await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Execute a hand with the given input
|
/// Execute a hand with the given input, tracking the run
|
||||||
pub async fn execute_hand(
|
pub async fn execute_hand(
|
||||||
&self,
|
&self,
|
||||||
hand_id: &str,
|
hand_id: &str,
|
||||||
input: serde_json::Value,
|
input: serde_json::Value,
|
||||||
) -> Result<HandResult> {
|
) -> Result<(HandResult, HandRunId)> {
|
||||||
// Use default context (agent_id will be generated)
|
let run_id = HandRunId::new();
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
// Create the initial HandRun record
|
||||||
|
let mut run = HandRun {
|
||||||
|
id: run_id,
|
||||||
|
hand_name: hand_id.to_string(),
|
||||||
|
trigger_source: TriggerSource::Manual,
|
||||||
|
params: input.clone(),
|
||||||
|
status: HandRunStatus::Pending,
|
||||||
|
result: None,
|
||||||
|
error: None,
|
||||||
|
duration_ms: None,
|
||||||
|
created_at: now.clone(),
|
||||||
|
started_at: None,
|
||||||
|
completed_at: None,
|
||||||
|
};
|
||||||
|
self.memory.save_hand_run(&run).await?;
|
||||||
|
|
||||||
|
// Transition to Running
|
||||||
|
run.status = HandRunStatus::Running;
|
||||||
|
run.started_at = Some(chrono::Utc::now().to_rfc3339());
|
||||||
|
self.memory.update_hand_run(&run).await?;
|
||||||
|
|
||||||
|
// Register cancellation flag
|
||||||
|
let cancel_flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||||
|
self.running_hand_runs.insert(run_id, cancel_flag.clone());
|
||||||
|
|
||||||
|
// Execute the hand
|
||||||
let context = HandContext::default();
|
let context = HandContext::default();
|
||||||
self.hands.execute(hand_id, &context, input).await
|
let start = std::time::Instant::now();
|
||||||
|
let hand_result = self.hands.execute(hand_id, &context, input).await;
|
||||||
|
let duration = start.elapsed();
|
||||||
|
|
||||||
|
// Check if cancelled during execution
|
||||||
|
if cancel_flag.load(std::sync::atomic::Ordering::Relaxed) {
|
||||||
|
let mut run_update = run.clone();
|
||||||
|
run_update.status = HandRunStatus::Cancelled;
|
||||||
|
run_update.completed_at = Some(chrono::Utc::now().to_rfc3339());
|
||||||
|
run_update.duration_ms = Some(duration.as_millis() as u64);
|
||||||
|
self.memory.update_hand_run(&run_update).await?;
|
||||||
|
self.running_hand_runs.remove(&run_id);
|
||||||
|
return Err(zclaw_types::ZclawError::Internal("Hand execution cancelled".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove from running map
|
||||||
|
self.running_hand_runs.remove(&run_id);
|
||||||
|
|
||||||
|
// Update HandRun with result
|
||||||
|
let completed_at = chrono::Utc::now().to_rfc3339();
|
||||||
|
match &hand_result {
|
||||||
|
Ok(res) => {
|
||||||
|
run.status = HandRunStatus::Completed;
|
||||||
|
run.result = Some(res.output.clone());
|
||||||
|
run.error = res.error.clone();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
run.status = HandRunStatus::Failed;
|
||||||
|
run.error = Some(e.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
run.duration_ms = Some(duration.as_millis() as u64);
|
||||||
|
run.completed_at = Some(completed_at);
|
||||||
|
self.memory.update_hand_run(&run).await?;
|
||||||
|
|
||||||
|
hand_result.map(|res| (res, run_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Execute a hand with a specific trigger source (for scheduled/event triggers)
|
||||||
|
pub async fn execute_hand_with_source(
|
||||||
|
&self,
|
||||||
|
hand_id: &str,
|
||||||
|
input: serde_json::Value,
|
||||||
|
trigger_source: TriggerSource,
|
||||||
|
) -> Result<(HandResult, HandRunId)> {
|
||||||
|
let run_id = HandRunId::new();
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
let mut run = HandRun {
|
||||||
|
id: run_id,
|
||||||
|
hand_name: hand_id.to_string(),
|
||||||
|
trigger_source,
|
||||||
|
params: input.clone(),
|
||||||
|
status: HandRunStatus::Pending,
|
||||||
|
result: None,
|
||||||
|
error: None,
|
||||||
|
duration_ms: None,
|
||||||
|
created_at: now,
|
||||||
|
started_at: None,
|
||||||
|
completed_at: None,
|
||||||
|
};
|
||||||
|
self.memory.save_hand_run(&run).await?;
|
||||||
|
|
||||||
|
run.status = HandRunStatus::Running;
|
||||||
|
run.started_at = Some(chrono::Utc::now().to_rfc3339());
|
||||||
|
self.memory.update_hand_run(&run).await?;
|
||||||
|
|
||||||
|
let cancel_flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||||
|
self.running_hand_runs.insert(run_id, cancel_flag.clone());
|
||||||
|
|
||||||
|
let context = HandContext::default();
|
||||||
|
let start = std::time::Instant::now();
|
||||||
|
let hand_result = self.hands.execute(hand_id, &context, input).await;
|
||||||
|
let duration = start.elapsed();
|
||||||
|
|
||||||
|
// Check if cancelled during execution
|
||||||
|
if cancel_flag.load(std::sync::atomic::Ordering::Relaxed) {
|
||||||
|
run.status = HandRunStatus::Cancelled;
|
||||||
|
run.completed_at = Some(chrono::Utc::now().to_rfc3339());
|
||||||
|
run.duration_ms = Some(duration.as_millis() as u64);
|
||||||
|
self.memory.update_hand_run(&run).await?;
|
||||||
|
self.running_hand_runs.remove(&run_id);
|
||||||
|
return Err(zclaw_types::ZclawError::Internal("Hand execution cancelled".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
self.running_hand_runs.remove(&run_id);
|
||||||
|
|
||||||
|
let completed_at = chrono::Utc::now().to_rfc3339();
|
||||||
|
match &hand_result {
|
||||||
|
Ok(res) => {
|
||||||
|
run.status = HandRunStatus::Completed;
|
||||||
|
run.result = Some(res.output.clone());
|
||||||
|
run.error = res.error.clone();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
run.status = HandRunStatus::Failed;
|
||||||
|
run.error = Some(e.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
run.duration_ms = Some(duration.as_millis() as u64);
|
||||||
|
run.completed_at = Some(completed_at);
|
||||||
|
self.memory.update_hand_run(&run).await?;
|
||||||
|
|
||||||
|
hand_result.map(|res| (res, run_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Hand Run Tracking
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
/// Get a hand run by ID
|
||||||
|
pub async fn get_hand_run(&self, id: &HandRunId) -> Result<Option<HandRun>> {
|
||||||
|
self.memory.get_hand_run(id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// List hand runs with filter
|
||||||
|
pub async fn list_hand_runs(&self, filter: &HandRunFilter) -> Result<Vec<HandRun>> {
|
||||||
|
self.memory.list_hand_runs(filter).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Count hand runs matching filter
|
||||||
|
pub async fn count_hand_runs(&self, filter: &HandRunFilter) -> Result<u32> {
|
||||||
|
self.memory.count_hand_runs(filter).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel a running hand execution
|
||||||
|
pub async fn cancel_hand_run(&self, id: &HandRunId) -> Result<()> {
|
||||||
|
if let Some((_, flag)) = self.running_hand_runs.remove(id) {
|
||||||
|
flag.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
|
||||||
|
// Note: the actual status update happens in execute_hand_with_source
|
||||||
|
// when it detects the cancel flag
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
// Not currently running — check if exists at all
|
||||||
|
let run = self.memory.get_hand_run(id).await?;
|
||||||
|
match run {
|
||||||
|
Some(r) if r.status == HandRunStatus::Pending => {
|
||||||
|
let mut updated = r;
|
||||||
|
updated.status = HandRunStatus::Cancelled;
|
||||||
|
updated.completed_at = Some(chrono::Utc::now().to_rfc3339());
|
||||||
|
self.memory.update_hand_run(&updated).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some(r) => Err(zclaw_types::ZclawError::InvalidInput(
|
||||||
|
format!("Cannot cancel hand run {} with status {}", id, r.status)
|
||||||
|
)),
|
||||||
|
None => Err(zclaw_types::ZclawError::NotFound(
|
||||||
|
format!("Hand run {} not found", id)
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
@@ -563,6 +831,7 @@ impl Kernel {
|
|||||||
status: "pending".to_string(),
|
status: "pending".to_string(),
|
||||||
created_at: chrono::Utc::now(),
|
created_at: chrono::Utc::now(),
|
||||||
input,
|
input,
|
||||||
|
reject_reason: None,
|
||||||
};
|
};
|
||||||
let mut approvals = self.pending_approvals.lock().await;
|
let mut approvals = self.pending_approvals.lock().await;
|
||||||
approvals.push(entry.clone());
|
approvals.push(entry.clone());
|
||||||
@@ -574,13 +843,16 @@ impl Kernel {
|
|||||||
&self,
|
&self,
|
||||||
id: &str,
|
id: &str,
|
||||||
approved: bool,
|
approved: bool,
|
||||||
_reason: Option<String>,
|
reason: Option<String>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let mut approvals = self.pending_approvals.lock().await;
|
let mut approvals = self.pending_approvals.lock().await;
|
||||||
let entry = approvals.iter_mut().find(|a| a.id == id && a.status == "pending")
|
let entry = approvals.iter_mut().find(|a| a.id == id && a.status == "pending")
|
||||||
.ok_or_else(|| zclaw_types::ZclawError::NotFound(format!("Approval not found: {}", id)))?;
|
.ok_or_else(|| zclaw_types::ZclawError::NotFound(format!("Approval not found: {}", id)))?;
|
||||||
|
|
||||||
entry.status = if approved { "approved".to_string() } else { "rejected".to_string() };
|
entry.status = if approved { "approved".to_string() } else { "rejected".to_string() };
|
||||||
|
if let Some(r) = reason {
|
||||||
|
entry.reject_reason = Some(r);
|
||||||
|
}
|
||||||
|
|
||||||
if approved {
|
if approved {
|
||||||
let hand_id = entry.hand_id.clone();
|
let hand_id = entry.hand_id.clone();
|
||||||
@@ -623,9 +895,268 @@ impl Kernel {
|
|||||||
entry.status = "cancelled".to_string();
|
entry.status = "cancelled".to_string();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Approval entry for pending approvals
|
// ============================================================
|
||||||
|
// A2A (Agent-to-Agent) Messaging
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
/// Derive an A2A agent profile from an AgentConfig
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
fn agent_config_to_a2a_profile(config: &AgentConfig) -> A2aAgentProfile {
|
||||||
|
let caps: Vec<A2aCapability> = config.tools.iter().map(|tool_name| {
|
||||||
|
A2aCapability {
|
||||||
|
name: tool_name.clone(),
|
||||||
|
description: format!("Tool: {}", tool_name),
|
||||||
|
input_schema: None,
|
||||||
|
output_schema: None,
|
||||||
|
requires_approval: false,
|
||||||
|
version: "1.0.0".to_string(),
|
||||||
|
tags: vec![],
|
||||||
|
}
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
A2aAgentProfile {
|
||||||
|
id: config.id,
|
||||||
|
name: config.name.clone(),
|
||||||
|
description: config.description.clone().unwrap_or_default(),
|
||||||
|
capabilities: caps,
|
||||||
|
protocols: vec!["a2a".to_string()],
|
||||||
|
role: "worker".to_string(),
|
||||||
|
priority: 5,
|
||||||
|
metadata: std::collections::HashMap::new(),
|
||||||
|
groups: vec![],
|
||||||
|
last_seen: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if an agent is authorized to send messages to a target
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
fn check_a2a_permission(&self, from: &AgentId, to: &AgentId) -> Result<()> {
|
||||||
|
let caps = self.capabilities.get(from);
|
||||||
|
match caps {
|
||||||
|
Some(cap_set) => {
|
||||||
|
let has_permission = cap_set.capabilities.iter().any(|cap| {
|
||||||
|
match cap {
|
||||||
|
Capability::AgentMessage { pattern } => {
|
||||||
|
pattern == "*" || to.to_string().starts_with(pattern)
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if !has_permission {
|
||||||
|
return Err(zclaw_types::ZclawError::PermissionDenied(
|
||||||
|
format!("Agent {} does not have AgentMessage capability for {}", from, to)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// No capabilities registered — deny by default
|
||||||
|
Err(zclaw_types::ZclawError::PermissionDenied(
|
||||||
|
format!("Agent {} has no capabilities registered", from)
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send a direct A2A message from one agent to another
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
pub async fn a2a_send(
|
||||||
|
&self,
|
||||||
|
from: &AgentId,
|
||||||
|
to: &AgentId,
|
||||||
|
payload: serde_json::Value,
|
||||||
|
message_type: Option<A2aMessageType>,
|
||||||
|
) -> Result<()> {
|
||||||
|
// Validate sender exists
|
||||||
|
self.registry.get(from)
|
||||||
|
.ok_or_else(|| zclaw_types::ZclawError::NotFound(
|
||||||
|
format!("Sender agent not found: {}", from)
|
||||||
|
))?;
|
||||||
|
|
||||||
|
// Validate receiver exists and is running
|
||||||
|
self.registry.get(to)
|
||||||
|
.ok_or_else(|| zclaw_types::ZclawError::NotFound(
|
||||||
|
format!("Target agent not found: {}", to)
|
||||||
|
))?;
|
||||||
|
|
||||||
|
// Check capability permission
|
||||||
|
self.check_a2a_permission(from, to)?;
|
||||||
|
|
||||||
|
// Build and route envelope
|
||||||
|
let envelope = A2aEnvelope::new(
|
||||||
|
*from,
|
||||||
|
A2aRecipient::Direct { agent_id: *to },
|
||||||
|
message_type.unwrap_or(A2aMessageType::Notification),
|
||||||
|
payload,
|
||||||
|
);
|
||||||
|
|
||||||
|
self.a2a_router.route(envelope).await?;
|
||||||
|
|
||||||
|
// Emit event
|
||||||
|
self.events.publish(Event::A2aMessageSent {
|
||||||
|
from: *from,
|
||||||
|
to: format!("{}", to),
|
||||||
|
message_type: "direct".to_string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Broadcast a message from one agent to all other agents
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
pub async fn a2a_broadcast(
|
||||||
|
&self,
|
||||||
|
from: &AgentId,
|
||||||
|
payload: serde_json::Value,
|
||||||
|
) -> Result<()> {
|
||||||
|
// Validate sender exists
|
||||||
|
self.registry.get(from)
|
||||||
|
.ok_or_else(|| zclaw_types::ZclawError::NotFound(
|
||||||
|
format!("Sender agent not found: {}", from)
|
||||||
|
))?;
|
||||||
|
|
||||||
|
let envelope = A2aEnvelope::new(
|
||||||
|
*from,
|
||||||
|
A2aRecipient::Broadcast,
|
||||||
|
A2aMessageType::Notification,
|
||||||
|
payload,
|
||||||
|
);
|
||||||
|
|
||||||
|
self.a2a_router.route(envelope).await?;
|
||||||
|
|
||||||
|
self.events.publish(Event::A2aMessageSent {
|
||||||
|
from: *from,
|
||||||
|
to: "broadcast".to_string(),
|
||||||
|
message_type: "broadcast".to_string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Discover agents that have a specific capability
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
pub async fn a2a_discover(&self, capability: &str) -> Result<Vec<A2aAgentProfile>> {
|
||||||
|
let result = self.a2a_router.discover(capability).await?;
|
||||||
|
|
||||||
|
self.events.publish(Event::A2aAgentDiscovered {
|
||||||
|
agent_id: AgentId::new(),
|
||||||
|
capabilities: vec![capability.to_string()],
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Try to receive a pending A2A message for an agent (non-blocking)
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
pub async fn a2a_receive(&self, agent_id: &AgentId) -> Result<Option<A2aEnvelope>> {
|
||||||
|
let inbox = self.a2a_inboxes.get(agent_id)
|
||||||
|
.ok_or_else(|| zclaw_types::ZclawError::NotFound(
|
||||||
|
format!("No A2A inbox for agent: {}", agent_id)
|
||||||
|
))?;
|
||||||
|
|
||||||
|
let mut rx = inbox.lock().await;
|
||||||
|
match rx.try_recv() {
|
||||||
|
Ok(envelope) => {
|
||||||
|
self.events.publish(Event::A2aMessageReceived {
|
||||||
|
from: envelope.from,
|
||||||
|
to: format!("{}", agent_id),
|
||||||
|
message_type: "direct".to_string(),
|
||||||
|
});
|
||||||
|
Ok(Some(envelope))
|
||||||
|
}
|
||||||
|
Err(_) => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delegate a task to another agent and wait for response with timeout
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
pub async fn a2a_delegate_task(
|
||||||
|
&self,
|
||||||
|
from: &AgentId,
|
||||||
|
to: &AgentId,
|
||||||
|
task_description: String,
|
||||||
|
timeout_ms: u64,
|
||||||
|
) -> Result<serde_json::Value> {
|
||||||
|
// Validate both agents exist
|
||||||
|
self.registry.get(from)
|
||||||
|
.ok_or_else(|| zclaw_types::ZclawError::NotFound(
|
||||||
|
format!("Sender agent not found: {}", from)
|
||||||
|
))?;
|
||||||
|
self.registry.get(to)
|
||||||
|
.ok_or_else(|| zclaw_types::ZclawError::NotFound(
|
||||||
|
format!("Target agent not found: {}", to)
|
||||||
|
))?;
|
||||||
|
|
||||||
|
// Check capability permission
|
||||||
|
self.check_a2a_permission(from, to)?;
|
||||||
|
|
||||||
|
// Send task request
|
||||||
|
let task_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let envelope = A2aEnvelope::new(
|
||||||
|
*from,
|
||||||
|
A2aRecipient::Direct { agent_id: *to },
|
||||||
|
A2aMessageType::Task,
|
||||||
|
serde_json::json!({
|
||||||
|
"task_id": task_id,
|
||||||
|
"description": task_description,
|
||||||
|
}),
|
||||||
|
).with_conversation(task_id.clone());
|
||||||
|
|
||||||
|
let envelope_id = envelope.id.clone();
|
||||||
|
self.a2a_router.route(envelope).await?;
|
||||||
|
|
||||||
|
self.events.publish(Event::A2aMessageSent {
|
||||||
|
from: *from,
|
||||||
|
to: format!("{}", to),
|
||||||
|
message_type: "task".to_string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wait for response with timeout
|
||||||
|
let timeout = tokio::time::Duration::from_millis(timeout_ms);
|
||||||
|
let result = tokio::time::timeout(timeout, async {
|
||||||
|
let inbox = self.a2a_inboxes.get(from)
|
||||||
|
.ok_or_else(|| zclaw_types::ZclawError::NotFound(
|
||||||
|
format!("No A2A inbox for agent: {}", from)
|
||||||
|
))?;
|
||||||
|
let mut rx = inbox.lock().await;
|
||||||
|
|
||||||
|
// Poll for matching response
|
||||||
|
loop {
|
||||||
|
match rx.recv().await {
|
||||||
|
Some(msg) => {
|
||||||
|
// Check if this is a response to our task
|
||||||
|
if msg.message_type == A2aMessageType::Response
|
||||||
|
&& msg.reply_to.as_deref() == Some(&envelope_id) {
|
||||||
|
return Ok::<_, zclaw_types::ZclawError>(msg.payload);
|
||||||
|
}
|
||||||
|
// Not our response — put it back by logging it (would need a re-queue mechanism for production)
|
||||||
|
tracing::warn!("Received non-matching A2A response, discarding: {}", msg.id);
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
return Err(zclaw_types::ZclawError::Internal(
|
||||||
|
"A2A inbox channel closed".to_string()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}).await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(Ok(payload)) => Ok(payload),
|
||||||
|
Ok(Err(e)) => Err(e),
|
||||||
|
Err(_) => Err(zclaw_types::ZclawError::Timeout(
|
||||||
|
format!("A2A task delegation timed out after {}ms", timeout_ms)
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get all online agents via A2A profiles
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
pub async fn a2a_get_online_agents(&self) -> Result<Vec<A2aAgentProfile>> {
|
||||||
|
Ok(self.a2a_router.list_profiles().await)
|
||||||
|
}
|
||||||
|
}
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct ApprovalEntry {
|
pub struct ApprovalEntry {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
@@ -633,6 +1164,7 @@ pub struct ApprovalEntry {
|
|||||||
pub status: String,
|
pub status: String,
|
||||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||||
pub input: serde_json::Value,
|
pub input: serde_json::Value,
|
||||||
|
pub reject_reason: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Response from sending a message
|
/// Response from sending a message
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ mod capabilities;
|
|||||||
mod events;
|
mod events;
|
||||||
pub mod trigger_manager;
|
pub mod trigger_manager;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
|
pub mod scheduler;
|
||||||
#[cfg(feature = "multi-agent")]
|
#[cfg(feature = "multi-agent")]
|
||||||
pub mod director;
|
pub mod director;
|
||||||
pub mod generation;
|
pub mod generation;
|
||||||
@@ -21,8 +22,16 @@ pub use config::*;
|
|||||||
pub use trigger_manager::{TriggerManager, TriggerEntry, TriggerUpdateRequest, TriggerManagerConfig};
|
pub use trigger_manager::{TriggerManager, TriggerEntry, TriggerUpdateRequest, TriggerManagerConfig};
|
||||||
#[cfg(feature = "multi-agent")]
|
#[cfg(feature = "multi-agent")]
|
||||||
pub use director::*;
|
pub use director::*;
|
||||||
|
#[cfg(feature = "multi-agent")]
|
||||||
|
pub use zclaw_protocols::{
|
||||||
|
A2aRouter, A2aAgentProfile, A2aCapability, A2aEnvelope, A2aMessageType, A2aRecipient,
|
||||||
|
A2aReceiver,
|
||||||
|
BasicA2aClient,
|
||||||
|
A2aClient,
|
||||||
|
};
|
||||||
pub use generation::*;
|
pub use generation::*;
|
||||||
pub use export::{ExportFormat, ExportOptions, ExportResult, Exporter, export_classroom};
|
pub use export::{ExportFormat, ExportOptions, ExportResult, Exporter, export_classroom};
|
||||||
|
|
||||||
// Re-export hands types for convenience
|
// Re-export hands types for convenience
|
||||||
pub use zclaw_hands::{HandRegistry, HandContext, HandResult, HandConfig, Hand, HandStatus};
|
pub use zclaw_hands::{HandRegistry, HandContext, HandResult, HandConfig, Hand, HandStatus};
|
||||||
|
pub use scheduler::SchedulerService;
|
||||||
|
|||||||
341
crates/zclaw-kernel/src/scheduler.rs
Normal file
341
crates/zclaw-kernel/src/scheduler.rs
Normal file
@@ -0,0 +1,341 @@
|
|||||||
|
//! Scheduler service for automatic trigger execution
|
||||||
|
//!
|
||||||
|
//! Periodically scans scheduled triggers and fires them at the appropriate time.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use chrono::{Datelike, Timelike};
|
||||||
|
use tokio::sync::RwLock;
|
||||||
|
use tokio::time::{self, Duration};
|
||||||
|
use zclaw_types::Result;
|
||||||
|
use crate::Kernel;
|
||||||
|
|
||||||
|
/// Scheduler service that runs in the background and executes scheduled triggers
|
||||||
|
pub struct SchedulerService {
|
||||||
|
kernel: Arc<RwLock<Option<Kernel>>>,
|
||||||
|
running: Arc<AtomicBool>,
|
||||||
|
check_interval: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SchedulerService {
|
||||||
|
/// Create a new scheduler service
|
||||||
|
pub fn new(kernel: Arc<RwLock<Option<Kernel>>>, check_interval_secs: u64) -> Self {
|
||||||
|
Self {
|
||||||
|
kernel,
|
||||||
|
running: Arc::new(AtomicBool::new(false)),
|
||||||
|
check_interval: Duration::from_secs(check_interval_secs),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the scheduler loop in the background
|
||||||
|
pub fn start(&self) {
|
||||||
|
if self.running.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_err() {
|
||||||
|
tracing::warn!("[Scheduler] Already running, ignoring start request");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let kernel = self.kernel.clone();
|
||||||
|
let running = self.running.clone();
|
||||||
|
let interval = self.check_interval;
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
tracing::info!("[Scheduler] Starting scheduler loop with {}s interval", interval.as_secs());
|
||||||
|
|
||||||
|
let mut ticker = time::interval(interval);
|
||||||
|
// First tick fires immediately — skip it
|
||||||
|
ticker.tick().await;
|
||||||
|
|
||||||
|
while running.load(Ordering::Relaxed) {
|
||||||
|
ticker.tick().await;
|
||||||
|
|
||||||
|
if !running.load(Ordering::Relaxed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(e) = Self::check_and_fire_scheduled_triggers(&kernel).await {
|
||||||
|
tracing::error!("[Scheduler] Error checking triggers: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!("[Scheduler] Scheduler loop stopped");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop the scheduler loop
|
||||||
|
pub fn stop(&self) {
|
||||||
|
self.running.store(false, Ordering::Relaxed);
|
||||||
|
tracing::info!("[Scheduler] Stop requested");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if the scheduler is running
|
||||||
|
pub fn is_running(&self) -> bool {
|
||||||
|
self.running.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check all scheduled triggers and fire those that are due
|
||||||
|
async fn check_and_fire_scheduled_triggers(
|
||||||
|
kernel_lock: &Arc<RwLock<Option<Kernel>>>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let kernel_read = kernel_lock.read().await;
|
||||||
|
let kernel = match kernel_read.as_ref() {
|
||||||
|
Some(k) => k,
|
||||||
|
None => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get all triggers
|
||||||
|
let triggers = kernel.list_triggers().await;
|
||||||
|
let now = chrono::Utc::now();
|
||||||
|
|
||||||
|
// Filter to enabled Schedule triggers
|
||||||
|
let scheduled: Vec<_> = triggers.iter()
|
||||||
|
.filter(|t| {
|
||||||
|
t.config.enabled && matches!(t.config.trigger_type, zclaw_hands::TriggerType::Schedule { .. })
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if scheduled.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::debug!("[Scheduler] Checking {} scheduled triggers", scheduled.len());
|
||||||
|
|
||||||
|
// Drop the read lock before executing
|
||||||
|
let to_execute: Vec<(String, String, String)> = scheduled.iter()
|
||||||
|
.filter_map(|t| {
|
||||||
|
if let zclaw_hands::TriggerType::Schedule { ref cron } = t.config.trigger_type {
|
||||||
|
// Simple cron matching: check if we should fire now
|
||||||
|
if Self::should_fire_cron(cron, &now) {
|
||||||
|
Some((t.config.id.clone(), t.config.hand_id.clone(), cron.clone()))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
drop(kernel_read);
|
||||||
|
|
||||||
|
// Execute due triggers (with write lock since execute_hand may need it)
|
||||||
|
for (trigger_id, hand_id, cron_expr) in to_execute {
|
||||||
|
tracing::info!(
|
||||||
|
"[Scheduler] Firing scheduled trigger '{}' → hand '{}' (cron: {})",
|
||||||
|
trigger_id, hand_id, cron_expr
|
||||||
|
);
|
||||||
|
|
||||||
|
let kernel_read = kernel_lock.read().await;
|
||||||
|
if let Some(kernel) = kernel_read.as_ref() {
|
||||||
|
let trigger_source = zclaw_types::TriggerSource::Scheduled {
|
||||||
|
trigger_id: trigger_id.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let input = serde_json::json!({
|
||||||
|
"trigger_id": trigger_id,
|
||||||
|
"trigger_type": "schedule",
|
||||||
|
"cron": cron_expr,
|
||||||
|
"fired_at": now.to_rfc3339(),
|
||||||
|
});
|
||||||
|
|
||||||
|
match kernel.execute_hand_with_source(&hand_id, input, trigger_source).await {
|
||||||
|
Ok((_result, run_id)) => {
|
||||||
|
tracing::info!(
|
||||||
|
"[Scheduler] Successfully fired trigger '{}' → run {}",
|
||||||
|
trigger_id, run_id
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(
|
||||||
|
"[Scheduler] Failed to execute trigger '{}': {}",
|
||||||
|
trigger_id, e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Simple cron expression matcher
|
||||||
|
///
|
||||||
|
/// Supports basic cron format: `minute hour day month weekday`
|
||||||
|
/// Also supports interval shorthand: `every:Ns`, `every:Nm`, `every:Nh`
|
||||||
|
fn should_fire_cron(cron: &str, now: &chrono::DateTime<chrono::Utc>) -> bool {
|
||||||
|
let cron = cron.trim();
|
||||||
|
|
||||||
|
// Handle interval shorthand: "every:30s", "every:5m", "every:1h"
|
||||||
|
if let Some(interval_str) = cron.strip_prefix("every:") {
|
||||||
|
return Self::check_interval_shorthand(interval_str, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle ISO timestamp for one-shot: "2026-03-29T10:00:00Z"
|
||||||
|
if cron.contains('T') && cron.contains('-') {
|
||||||
|
if let Ok(target) = chrono::DateTime::parse_from_rfc3339(cron) {
|
||||||
|
let target_utc = target.with_timezone(&chrono::Utc);
|
||||||
|
// Fire if within the check window (± check_interval/2, approx 30s)
|
||||||
|
let diff = (*now - target_utc).num_seconds().abs();
|
||||||
|
return diff <= 30;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard 5-field cron: minute hour day_of_month month day_of_week
|
||||||
|
let parts: Vec<&str> = cron.split_whitespace().collect();
|
||||||
|
if parts.len() != 5 {
|
||||||
|
tracing::warn!("[Scheduler] Invalid cron expression (expected 5 fields): '{}'", cron);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let minute = now.minute() as i32;
|
||||||
|
let hour = now.hour() as i32;
|
||||||
|
let day = now.day() as i32;
|
||||||
|
let month = now.month() as i32;
|
||||||
|
let weekday = now.weekday().num_days_from_monday() as i32; // Mon=0..Sun=6
|
||||||
|
|
||||||
|
Self::cron_field_matches(parts[0], minute)
|
||||||
|
&& Self::cron_field_matches(parts[1], hour)
|
||||||
|
&& Self::cron_field_matches(parts[2], day)
|
||||||
|
&& Self::cron_field_matches(parts[3], month)
|
||||||
|
&& Self::cron_field_matches(parts[4], weekday)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if a single cron field matches the current value
|
||||||
|
fn cron_field_matches(field: &str, value: i32) -> bool {
|
||||||
|
if field == "*" || field == "?" {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle step: */N
|
||||||
|
if let Some(step_str) = field.strip_prefix("*/") {
|
||||||
|
if let Ok(step) = step_str.parse::<i32>() {
|
||||||
|
if step > 0 {
|
||||||
|
return value % step == 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle range: N-M
|
||||||
|
if field.contains('-') {
|
||||||
|
let range_parts: Vec<&str> = field.split('-').collect();
|
||||||
|
if range_parts.len() == 2 {
|
||||||
|
if let (Ok(start), Ok(end)) = (range_parts[0].parse::<i32>(), range_parts[1].parse::<i32>()) {
|
||||||
|
return value >= start && value <= end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle list: N,M,O
|
||||||
|
if field.contains(',') {
|
||||||
|
return field.split(',').any(|part| {
|
||||||
|
part.trim().parse::<i32>().map(|p| p == value).unwrap_or(false)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simple value
|
||||||
|
field.parse::<i32>().map(|p| p == value).unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check interval shorthand expressions
|
||||||
|
fn check_interval_shorthand(interval: &str, now: &chrono::DateTime<chrono::Utc>) -> bool {
|
||||||
|
let (num_str, unit) = if interval.ends_with('s') {
|
||||||
|
(&interval[..interval.len()-1], 's')
|
||||||
|
} else if interval.ends_with('m') {
|
||||||
|
(&interval[..interval.len()-1], 'm')
|
||||||
|
} else if interval.ends_with('h') {
|
||||||
|
(&interval[..interval.len()-1], 'h')
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
let num: i64 = match num_str.parse() {
|
||||||
|
Ok(n) => n,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
|
||||||
|
if num <= 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let interval_secs = match unit {
|
||||||
|
's' => num,
|
||||||
|
'm' => num * 60,
|
||||||
|
'h' => num * 3600,
|
||||||
|
_ => return false,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check if current timestamp aligns with the interval
|
||||||
|
let timestamp = now.timestamp();
|
||||||
|
timestamp % interval_secs == 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use chrono::Timelike;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_cron_field_wildcard() {
|
||||||
|
assert!(SchedulerService::cron_field_matches("*", 5));
|
||||||
|
assert!(SchedulerService::cron_field_matches("?", 5));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_cron_field_exact() {
|
||||||
|
assert!(SchedulerService::cron_field_matches("5", 5));
|
||||||
|
assert!(!SchedulerService::cron_field_matches("5", 6));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_cron_field_step() {
|
||||||
|
assert!(SchedulerService::cron_field_matches("*/5", 0));
|
||||||
|
assert!(SchedulerService::cron_field_matches("*/5", 5));
|
||||||
|
assert!(SchedulerService::cron_field_matches("*/5", 10));
|
||||||
|
assert!(!SchedulerService::cron_field_matches("*/5", 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_cron_field_range() {
|
||||||
|
assert!(SchedulerService::cron_field_matches("1-5", 1));
|
||||||
|
assert!(SchedulerService::cron_field_matches("1-5", 3));
|
||||||
|
assert!(SchedulerService::cron_field_matches("1-5", 5));
|
||||||
|
assert!(!SchedulerService::cron_field_matches("1-5", 0));
|
||||||
|
assert!(!SchedulerService::cron_field_matches("1-5", 6));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_cron_field_list() {
|
||||||
|
assert!(SchedulerService::cron_field_matches("1,3,5", 1));
|
||||||
|
assert!(SchedulerService::cron_field_matches("1,3,5", 3));
|
||||||
|
assert!(SchedulerService::cron_field_matches("1,3,5", 5));
|
||||||
|
assert!(!SchedulerService::cron_field_matches("1,3,5", 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_should_fire_every_minute() {
|
||||||
|
let now = chrono::Utc::now();
|
||||||
|
assert!(SchedulerService::should_fire_cron("every:1m", &now));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_should_fire_cron_wildcard() {
|
||||||
|
let now = chrono::Utc::now();
|
||||||
|
// Every minute match
|
||||||
|
assert!(SchedulerService::should_fire_cron(
|
||||||
|
&format!("{} * * * *", now.minute()),
|
||||||
|
&now,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_should_not_fire_cron() {
|
||||||
|
let now = chrono::Utc::now();
|
||||||
|
let wrong_minute = if now.minute() < 59 { now.minute() + 1 } else { 0 };
|
||||||
|
assert!(!SchedulerService::should_fire_cron(
|
||||||
|
&format!("{} * * * *", wrong_minute),
|
||||||
|
&now,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -49,8 +49,26 @@ CREATE TABLE IF NOT EXISTS schema_version (
|
|||||||
version INTEGER PRIMARY KEY
|
version INTEGER PRIMARY KEY
|
||||||
);
|
);
|
||||||
|
|
||||||
|
-- Hand execution runs table
|
||||||
|
CREATE TABLE IF NOT EXISTS hand_runs (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
hand_name TEXT NOT NULL,
|
||||||
|
trigger_source TEXT NOT NULL,
|
||||||
|
params TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending',
|
||||||
|
result TEXT,
|
||||||
|
error TEXT,
|
||||||
|
duration_ms INTEGER,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
started_at TEXT,
|
||||||
|
completed_at TEXT
|
||||||
|
);
|
||||||
|
|
||||||
-- Indexes
|
-- Indexes
|
||||||
CREATE INDEX IF NOT EXISTS idx_sessions_agent ON sessions(agent_id);
|
CREATE INDEX IF NOT EXISTS idx_sessions_agent ON sessions(agent_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id);
|
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_kv_agent ON kv_store(agent_id);
|
CREATE INDEX IF NOT EXISTS idx_kv_agent ON kv_store(agent_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_hand_runs_hand ON hand_runs(hand_name);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_hand_runs_status ON hand_runs(status);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_hand_runs_created ON hand_runs(created_at);
|
||||||
"#;
|
"#;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
//! Memory store implementation
|
//! Memory store implementation
|
||||||
|
|
||||||
use sqlx::SqlitePool;
|
use sqlx::SqlitePool;
|
||||||
use zclaw_types::{AgentConfig, AgentId, SessionId, Message, Result, ZclawError};
|
use zclaw_types::{AgentConfig, AgentId, SessionId, Message, Result, ZclawError, HandRun, HandRunId, HandRunStatus, HandRunFilter};
|
||||||
|
|
||||||
/// Memory store for persisting ZCLAW data
|
/// Memory store for persisting ZCLAW data
|
||||||
pub struct MemoryStore {
|
pub struct MemoryStore {
|
||||||
@@ -283,6 +283,193 @@ impl MemoryStore {
|
|||||||
|
|
||||||
Ok(rows.into_iter().map(|(key,)| key).collect())
|
Ok(rows.into_iter().map(|(key,)| key).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// === Hand Run Tracking ===
|
||||||
|
|
||||||
|
/// Save a new hand run record
|
||||||
|
pub async fn save_hand_run(&self, run: &HandRun) -> Result<()> {
|
||||||
|
let id = run.id.to_string();
|
||||||
|
let trigger_source = serde_json::to_string(&run.trigger_source)?;
|
||||||
|
let params = serde_json::to_string(&run.params)?;
|
||||||
|
let result = run.result.as_ref().map(|v| serde_json::to_string(v)).transpose()?;
|
||||||
|
let error = run.error.as_ref().map(|e| serde_json::to_string(e)).transpose()?;
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
INSERT INTO hand_runs (id, hand_name, trigger_source, params, status, result, error, duration_ms, created_at, started_at, completed_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.bind(&id)
|
||||||
|
.bind(&run.hand_name)
|
||||||
|
.bind(&trigger_source)
|
||||||
|
.bind(¶ms)
|
||||||
|
.bind(run.status.to_string())
|
||||||
|
.bind(result.as_deref())
|
||||||
|
.bind(error.as_deref())
|
||||||
|
.bind(run.duration_ms.map(|d| d as i64))
|
||||||
|
.bind(&run.created_at)
|
||||||
|
.bind(run.started_at.as_deref())
|
||||||
|
.bind(run.completed_at.as_deref())
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| ZclawError::StorageError(e.to_string()))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update an existing hand run record
|
||||||
|
pub async fn update_hand_run(&self, run: &HandRun) -> Result<()> {
|
||||||
|
let id = run.id.to_string();
|
||||||
|
let trigger_source = serde_json::to_string(&run.trigger_source)?;
|
||||||
|
let params = serde_json::to_string(&run.params)?;
|
||||||
|
let result = run.result.as_ref().map(|v| serde_json::to_string(v)).transpose()?;
|
||||||
|
let error = run.error.as_ref().map(|e| serde_json::to_string(e)).transpose()?;
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
UPDATE hand_runs SET
|
||||||
|
hand_name = ?, trigger_source = ?, params = ?, status = ?,
|
||||||
|
result = ?, error = ?, duration_ms = ?,
|
||||||
|
started_at = ?, completed_at = ?
|
||||||
|
WHERE id = ?
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.bind(&run.hand_name)
|
||||||
|
.bind(&trigger_source)
|
||||||
|
.bind(¶ms)
|
||||||
|
.bind(run.status.to_string())
|
||||||
|
.bind(result.as_deref())
|
||||||
|
.bind(error.as_deref())
|
||||||
|
.bind(run.duration_ms.map(|d| d as i64))
|
||||||
|
.bind(run.started_at.as_deref())
|
||||||
|
.bind(run.completed_at.as_deref())
|
||||||
|
.bind(&id)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| ZclawError::StorageError(e.to_string()))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get a hand run by ID
|
||||||
|
pub async fn get_hand_run(&self, id: &HandRunId) -> Result<Option<HandRun>> {
|
||||||
|
let id_str = id.to_string();
|
||||||
|
|
||||||
|
let row = sqlx::query_as::<_, (String, String, String, String, String, Option<String>, Option<String>, Option<i64>, String, Option<String>, Option<String>)>(
|
||||||
|
"SELECT id, hand_name, trigger_source, params, status, result, error, duration_ms, created_at, started_at, completed_at FROM hand_runs WHERE id = ?"
|
||||||
|
)
|
||||||
|
.bind(&id_str)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| ZclawError::StorageError(e.to_string()))?;
|
||||||
|
|
||||||
|
match row {
|
||||||
|
Some(r) => Ok(Some(Self::row_to_hand_run(r)?)),
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// List hand runs with optional filter
|
||||||
|
pub async fn list_hand_runs(&self, filter: &HandRunFilter) -> Result<Vec<HandRun>> {
|
||||||
|
let mut query = String::from(
|
||||||
|
"SELECT id, hand_name, trigger_source, params, status, result, error, duration_ms, created_at, started_at, completed_at FROM hand_runs WHERE 1=1"
|
||||||
|
);
|
||||||
|
let mut bind_values: Vec<String> = Vec::new();
|
||||||
|
|
||||||
|
if let Some(ref hand_name) = filter.hand_name {
|
||||||
|
query.push_str(" AND hand_name = ?");
|
||||||
|
bind_values.push(hand_name.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(ref status) = filter.status {
|
||||||
|
query.push_str(" AND status = ?");
|
||||||
|
bind_values.push(status.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
query.push_str(" ORDER BY created_at DESC");
|
||||||
|
|
||||||
|
if let Some(limit) = filter.limit {
|
||||||
|
query.push_str(&format!(" LIMIT {}", limit));
|
||||||
|
}
|
||||||
|
if let Some(offset) = filter.offset {
|
||||||
|
query.push_str(&format!(" OFFSET {}", offset));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut sql_query = sqlx::query_as::<_, (String, String, String, String, String, Option<String>, Option<String>, Option<i64>, String, Option<String>, Option<String>)>(&query);
|
||||||
|
|
||||||
|
for val in &bind_values {
|
||||||
|
sql_query = sql_query.bind(val);
|
||||||
|
}
|
||||||
|
|
||||||
|
let rows = sql_query
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| ZclawError::StorageError(e.to_string()))?;
|
||||||
|
|
||||||
|
rows.into_iter()
|
||||||
|
.map(|r| Self::row_to_hand_run(r))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Count hand runs matching filter
|
||||||
|
pub async fn count_hand_runs(&self, filter: &HandRunFilter) -> Result<u32> {
|
||||||
|
let mut query = String::from("SELECT COUNT(*) FROM hand_runs WHERE 1=1");
|
||||||
|
let mut bind_values: Vec<String> = Vec::new();
|
||||||
|
|
||||||
|
if let Some(ref hand_name) = filter.hand_name {
|
||||||
|
query.push_str(" AND hand_name = ?");
|
||||||
|
bind_values.push(hand_name.clone());
|
||||||
|
}
|
||||||
|
if let Some(ref status) = filter.status {
|
||||||
|
query.push_str(" AND status = ?");
|
||||||
|
bind_values.push(status.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut sql_query = sqlx::query_scalar::<_, i64>(&query);
|
||||||
|
for val in &bind_values {
|
||||||
|
sql_query = sql_query.bind(val);
|
||||||
|
}
|
||||||
|
|
||||||
|
let count = sql_query
|
||||||
|
.fetch_one(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| ZclawError::StorageError(e.to_string()))?;
|
||||||
|
|
||||||
|
Ok(count as u32)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn row_to_hand_run(
|
||||||
|
row: (String, String, String, String, String, Option<String>, Option<String>, Option<i64>, String, Option<String>, Option<String>),
|
||||||
|
) -> Result<HandRun> {
|
||||||
|
let (id, hand_name, trigger_source, params, status, result, error, duration_ms, created_at, started_at, completed_at) = row;
|
||||||
|
|
||||||
|
let run_id: HandRunId = id.parse()
|
||||||
|
.map_err(|e| ZclawError::StorageError(format!("Invalid HandRunId: {}", e)))?;
|
||||||
|
let trigger: zclaw_types::TriggerSource = serde_json::from_str(&trigger_source)?;
|
||||||
|
let params_val: serde_json::Value = serde_json::from_str(¶ms)?;
|
||||||
|
let run_status: HandRunStatus = status.parse()
|
||||||
|
.map_err(|e| ZclawError::StorageError(e))?;
|
||||||
|
let result_val: Option<serde_json::Value> = result.map(|r| serde_json::from_str(&r)).transpose()?;
|
||||||
|
let error_val: Option<String> = error.as_ref()
|
||||||
|
.map(|e| serde_json::from_str::<String>(e))
|
||||||
|
.transpose()
|
||||||
|
.unwrap_or_else(|_| error.clone());
|
||||||
|
|
||||||
|
Ok(HandRun {
|
||||||
|
id: run_id,
|
||||||
|
hand_name,
|
||||||
|
trigger_source: trigger,
|
||||||
|
params: params_val,
|
||||||
|
status: run_status,
|
||||||
|
result: result_val,
|
||||||
|
error: error_val,
|
||||||
|
duration_ms: duration_ms.map(|d| d as u64),
|
||||||
|
created_at,
|
||||||
|
started_at,
|
||||||
|
completed_at,
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -427,6 +427,28 @@ impl A2aRouter {
|
|||||||
pub fn agent_id(&self) -> &AgentId {
|
pub fn agent_id(&self) -> &AgentId {
|
||||||
&self.agent_id
|
&self.agent_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Discover agents that have a specific capability
|
||||||
|
pub async fn discover(&self, capability: &str) -> Result<Vec<A2aAgentProfile>> {
|
||||||
|
let cap_index = self.capability_index.read().await;
|
||||||
|
let profiles = self.profiles.read().await;
|
||||||
|
|
||||||
|
match cap_index.get(capability) {
|
||||||
|
Some(agent_ids) => {
|
||||||
|
let result: Vec<A2aAgentProfile> = agent_ids.iter()
|
||||||
|
.filter_map(|id| profiles.get(id).cloned())
|
||||||
|
.collect();
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
None => Ok(Vec::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get all registered agent profiles
|
||||||
|
pub async fn list_profiles(&self) -> Vec<A2aAgentProfile> {
|
||||||
|
let profiles = self.profiles.read().await;
|
||||||
|
profiles.values().cloned().collect()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Basic A2A client implementation
|
/// Basic A2A client implementation
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
//! Optionally flushes old messages to the growth/memory system before discarding.
|
//! Optionally flushes old messages to the growth/memory system before discarding.
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
use zclaw_types::{AgentId, Message, SessionId};
|
use zclaw_types::{AgentId, Message, SessionId};
|
||||||
|
|
||||||
use crate::driver::{CompletionRequest, ContentBlock, LlmDriver};
|
use crate::driver::{CompletionRequest, ContentBlock, LlmDriver};
|
||||||
@@ -40,9 +41,18 @@ pub fn estimate_tokens(text: &str) -> usize {
|
|||||||
{
|
{
|
||||||
// CJK ideographs — ~1.5 tokens
|
// CJK ideographs — ~1.5 tokens
|
||||||
tokens += 1.5;
|
tokens += 1.5;
|
||||||
|
} else if (0xAC00..=0xD7AF).contains(&code) || (0x1100..=0x11FF).contains(&code) {
|
||||||
|
// Korean Hangul syllables + Jamo — ~1.5 tokens
|
||||||
|
tokens += 1.5;
|
||||||
|
} else if (0x3040..=0x309F).contains(&code) || (0x30A0..=0x30FF).contains(&code) {
|
||||||
|
// Japanese Hiragana + Katakana — ~1.5 tokens
|
||||||
|
tokens += 1.5;
|
||||||
} else if (0x3000..=0x303F).contains(&code) || (0xFF00..=0xFFEF).contains(&code) {
|
} else if (0x3000..=0x303F).contains(&code) || (0xFF00..=0xFFEF).contains(&code) {
|
||||||
// CJK / fullwidth punctuation — ~1.0 token
|
// CJK / fullwidth punctuation — ~1.0 token
|
||||||
tokens += 1.0;
|
tokens += 1.0;
|
||||||
|
} else if (0x1F000..=0x1FAFF).contains(&code) || (0x2600..=0x27BF).contains(&code) {
|
||||||
|
// Emoji & Symbols — ~2.0 tokens
|
||||||
|
tokens += 2.0;
|
||||||
} else if char == ' ' || char == '\n' || char == '\t' {
|
} else if char == ' ' || char == '\n' || char == '\t' {
|
||||||
// whitespace
|
// whitespace
|
||||||
tokens += 0.25;
|
tokens += 0.25;
|
||||||
@@ -88,6 +98,54 @@ pub fn estimate_messages_tokens(messages: &[Message]) -> usize {
|
|||||||
total
|
total
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Calibration: adjust heuristic estimates using API feedback
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
const F64_1_0_BITS: u64 = 4607182418800017408u64; // 1.0f64.to_bits()
|
||||||
|
|
||||||
|
/// Global calibration factor for token estimation (stored as f64 bits).
|
||||||
|
///
|
||||||
|
/// Updated via exponential moving average when API returns actual token counts.
|
||||||
|
/// Initial value is 1.0 (no adjustment).
|
||||||
|
static CALIBRATION_FACTOR_BITS: AtomicU64 = AtomicU64::new(F64_1_0_BITS);
|
||||||
|
|
||||||
|
/// Get the current calibration factor.
|
||||||
|
pub fn get_calibration_factor() -> f64 {
|
||||||
|
f64::from_bits(CALIBRATION_FACTOR_BITS.load(Ordering::Relaxed))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update calibration factor using exponential moving average.
|
||||||
|
///
|
||||||
|
/// Compares estimated tokens with actual tokens from API response:
|
||||||
|
/// - `ratio = actual / estimated` so underestimates push factor UP
|
||||||
|
/// - EMA: `new = current * 0.7 + ratio * 0.3`
|
||||||
|
/// - Clamped to [0.5, 2.0] to prevent runaway values
|
||||||
|
pub fn update_calibration(estimated: usize, actual: u32) {
|
||||||
|
if actual == 0 || estimated == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let ratio = actual as f64 / estimated as f64;
|
||||||
|
let current = get_calibration_factor();
|
||||||
|
let new_factor = (current * 0.7 + ratio * 0.3).clamp(0.5, 2.0);
|
||||||
|
CALIBRATION_FACTOR_BITS.store(new_factor.to_bits(), Ordering::Relaxed);
|
||||||
|
tracing::debug!(
|
||||||
|
"[Compaction] Calibration: estimated={}, actual={}, ratio={:.2}, factor {:.2} → {:.2}",
|
||||||
|
estimated, actual, ratio, current, new_factor
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Estimate total tokens for messages with calibration applied.
|
||||||
|
fn estimate_messages_tokens_calibrated(messages: &[Message]) -> usize {
|
||||||
|
let raw = estimate_messages_tokens(messages);
|
||||||
|
let factor = get_calibration_factor();
|
||||||
|
if (factor - 1.0).abs() < f64::EPSILON {
|
||||||
|
raw
|
||||||
|
} else {
|
||||||
|
((raw as f64 * factor).ceil()) as usize
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Compact a message list by summarizing old messages and keeping recent ones.
|
/// Compact a message list by summarizing old messages and keeping recent ones.
|
||||||
///
|
///
|
||||||
/// When `messages.len() > keep_recent`, the oldest messages are summarized
|
/// When `messages.len() > keep_recent`, the oldest messages are summarized
|
||||||
@@ -134,7 +192,7 @@ pub fn compact_messages(messages: Vec<Message>, keep_recent: usize) -> (Vec<Mess
|
|||||||
///
|
///
|
||||||
/// Returns the (possibly compacted) message list.
|
/// Returns the (possibly compacted) message list.
|
||||||
pub fn maybe_compact(messages: Vec<Message>, threshold: usize) -> Vec<Message> {
|
pub fn maybe_compact(messages: Vec<Message>, threshold: usize) -> Vec<Message> {
|
||||||
let tokens = estimate_messages_tokens(&messages);
|
let tokens = estimate_messages_tokens_calibrated(&messages);
|
||||||
if tokens < threshold {
|
if tokens < threshold {
|
||||||
return messages;
|
return messages;
|
||||||
}
|
}
|
||||||
@@ -208,7 +266,7 @@ pub async fn maybe_compact_with_config(
|
|||||||
driver: Option<&Arc<dyn LlmDriver>>,
|
driver: Option<&Arc<dyn LlmDriver>>,
|
||||||
growth: Option<&GrowthIntegration>,
|
growth: Option<&GrowthIntegration>,
|
||||||
) -> CompactionOutcome {
|
) -> CompactionOutcome {
|
||||||
let tokens = estimate_messages_tokens(&messages);
|
let tokens = estimate_messages_tokens_calibrated(&messages);
|
||||||
if tokens < threshold {
|
if tokens < threshold {
|
||||||
return CompactionOutcome {
|
return CompactionOutcome {
|
||||||
messages,
|
messages,
|
||||||
@@ -475,10 +533,11 @@ fn generate_summary(messages: &[Message]) -> String {
|
|||||||
|
|
||||||
let summary = sections.join("\n");
|
let summary = sections.join("\n");
|
||||||
|
|
||||||
// Enforce max length
|
// Enforce max length (char-safe for CJK)
|
||||||
let max_chars = 800;
|
let max_chars = 800;
|
||||||
if summary.len() > max_chars {
|
if summary.chars().count() > max_chars {
|
||||||
format!("{}...\n(摘要已截断)", &summary[..max_chars])
|
let truncated: String = summary.chars().take(max_chars).collect();
|
||||||
|
format!("{}...\n(摘要已截断)", truncated)
|
||||||
} else {
|
} else {
|
||||||
summary
|
summary
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,7 +130,8 @@ impl LlmDriver for OpenAiDriver {
|
|||||||
let api_key = self.api_key.expose_secret().to_string();
|
let api_key = self.api_key.expose_secret().to_string();
|
||||||
|
|
||||||
Box::pin(stream! {
|
Box::pin(stream! {
|
||||||
tracing::debug!("[OpenAiDriver:stream] Starting HTTP request...");
|
println!("[OpenAI:stream] POST to {}/chat/completions", base_url);
|
||||||
|
println!("[OpenAI:stream] Request model={}, stream={}", stream_request.model, stream_request.stream);
|
||||||
let response = match self.client
|
let response = match self.client
|
||||||
.post(format!("{}/chat/completions", base_url))
|
.post(format!("{}/chat/completions", base_url))
|
||||||
.header("Authorization", format!("Bearer {}", api_key))
|
.header("Authorization", format!("Bearer {}", api_key))
|
||||||
@@ -141,11 +142,11 @@ impl LlmDriver for OpenAiDriver {
|
|||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(r) => {
|
Ok(r) => {
|
||||||
tracing::debug!("[OpenAiDriver:stream] Got response, status: {}", r.status());
|
println!("[OpenAI:stream] Response status: {}, content-type: {:?}", r.status(), r.headers().get("content-type"));
|
||||||
r
|
r
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::error!("[OpenAiDriver:stream] HTTP request failed: {:?}", e);
|
println!("[OpenAI:stream] HTTP request FAILED: {:?}", e);
|
||||||
yield Err(ZclawError::LlmError(format!("HTTP request failed: {}", e)));
|
yield Err(ZclawError::LlmError(format!("HTTP request failed: {}", e)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -154,6 +155,7 @@ impl LlmDriver for OpenAiDriver {
|
|||||||
if !response.status().is_success() {
|
if !response.status().is_success() {
|
||||||
let status = response.status();
|
let status = response.status();
|
||||||
let body = response.text().await.unwrap_or_default();
|
let body = response.text().await.unwrap_or_default();
|
||||||
|
println!("[OpenAI:stream] API error {}: {}", status, &body[..body.len().min(500)]);
|
||||||
yield Err(ZclawError::LlmError(format!("API error {}: {}", status, body)));
|
yield Err(ZclawError::LlmError(format!("API error {}: {}", status, body)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -161,21 +163,45 @@ impl LlmDriver for OpenAiDriver {
|
|||||||
let mut byte_stream = response.bytes_stream();
|
let mut byte_stream = response.bytes_stream();
|
||||||
let mut accumulated_tool_calls: std::collections::HashMap<String, (String, String)> = std::collections::HashMap::new();
|
let mut accumulated_tool_calls: std::collections::HashMap<String, (String, String)> = std::collections::HashMap::new();
|
||||||
let mut current_tool_id: Option<String> = None;
|
let mut current_tool_id: Option<String> = None;
|
||||||
|
let mut sse_event_count: usize = 0;
|
||||||
|
let mut raw_bytes_total: usize = 0;
|
||||||
|
|
||||||
while let Some(chunk_result) = byte_stream.next().await {
|
while let Some(chunk_result) = byte_stream.next().await {
|
||||||
let chunk = match chunk_result {
|
let chunk = match chunk_result {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
println!("[OpenAI:stream] Byte stream error: {:?}", e);
|
||||||
yield Err(ZclawError::LlmError(format!("Stream error: {}", e)));
|
yield Err(ZclawError::LlmError(format!("Stream error: {}", e)));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
raw_bytes_total += chunk.len();
|
||||||
let text = String::from_utf8_lossy(&chunk);
|
let text = String::from_utf8_lossy(&chunk);
|
||||||
|
// Log first 500 bytes of raw data for debugging SSE format
|
||||||
|
if raw_bytes_total <= 600 {
|
||||||
|
println!("[OpenAI:stream] RAW chunk ({} bytes): {:?}", text.len(), &text[..text.len().min(500)]);
|
||||||
|
}
|
||||||
for line in text.lines() {
|
for line in text.lines() {
|
||||||
if let Some(data) = line.strip_prefix("data: ") {
|
let trimmed = line.trim();
|
||||||
|
if trimmed.is_empty() || trimmed.starts_with(':') {
|
||||||
|
continue; // Skip empty lines and SSE comments
|
||||||
|
}
|
||||||
|
// Handle both "data: " (standard) and "data:" (no space)
|
||||||
|
let data = if let Some(d) = trimmed.strip_prefix("data: ") {
|
||||||
|
Some(d)
|
||||||
|
} else if let Some(d) = trimmed.strip_prefix("data:") {
|
||||||
|
Some(d.trim_start())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if let Some(data) = data {
|
||||||
|
sse_event_count += 1;
|
||||||
|
if sse_event_count <= 3 || data == "[DONE]" {
|
||||||
|
println!("[OpenAI:stream] SSE #{}: {}", sse_event_count, &data[..data.len().min(300)]);
|
||||||
|
}
|
||||||
if data == "[DONE]" {
|
if data == "[DONE]" {
|
||||||
tracing::debug!("[OpenAI] Stream done, accumulated_tool_calls: {:?}", accumulated_tool_calls.len());
|
println!("[OpenAI:stream] Received [DONE], total SSE events: {}, raw bytes: {}", sse_event_count, raw_bytes_total);
|
||||||
|
|
||||||
// Emit ToolUseEnd for all accumulated tool calls (skip invalid ones with empty name)
|
// Emit ToolUseEnd for all accumulated tool calls (skip invalid ones with empty name)
|
||||||
for (id, (name, args)) in &accumulated_tool_calls {
|
for (id, (name, args)) in &accumulated_tool_calls {
|
||||||
@@ -216,10 +242,19 @@ impl LlmDriver for OpenAiDriver {
|
|||||||
// Handle text content
|
// Handle text content
|
||||||
if let Some(content) = &delta.content {
|
if let Some(content) = &delta.content {
|
||||||
if !content.is_empty() {
|
if !content.is_empty() {
|
||||||
|
tracing::debug!("[OpenAI:stream] TextDelta: {} chars", content.len());
|
||||||
yield Ok(StreamChunk::TextDelta { delta: content.clone() });
|
yield Ok(StreamChunk::TextDelta { delta: content.clone() });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle reasoning_content (Kimi, Qwen, DeepSeek, GLM thinking)
|
||||||
|
if let Some(reasoning) = &delta.reasoning_content {
|
||||||
|
if !reasoning.is_empty() {
|
||||||
|
tracing::debug!("[OpenAI:stream] ThinkingDelta (reasoning_content): {} chars", reasoning.len());
|
||||||
|
yield Ok(StreamChunk::ThinkingDelta { delta: reasoning.clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Handle tool calls
|
// Handle tool calls
|
||||||
if let Some(tool_calls) = &delta.tool_calls {
|
if let Some(tool_calls) = &delta.tool_calls {
|
||||||
tracing::trace!("[OpenAI] Received tool_calls delta: {:?}", tool_calls);
|
tracing::trace!("[OpenAI] Received tool_calls delta: {:?}", tool_calls);
|
||||||
@@ -284,6 +319,7 @@ impl LlmDriver for OpenAiDriver {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
println!("[OpenAI:stream] Byte stream ended. Total: {} SSE events, {} raw bytes", sse_event_count, raw_bytes_total);
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -304,55 +340,122 @@ impl OpenAiDriver {
|
|||||||
request.system.clone()
|
request.system.clone()
|
||||||
};
|
};
|
||||||
|
|
||||||
let messages: Vec<OpenAiMessage> = request.messages
|
// Build messages with tool result truncation to prevent payload overflow.
|
||||||
.iter()
|
// Most LLM APIs have a 2-4MB HTTP payload limit.
|
||||||
.filter_map(|msg| match msg {
|
const MAX_TOOL_RESULT_BYTES: usize = 32_768; // 32KB per tool result
|
||||||
zclaw_types::Message::User { content } => Some(OpenAiMessage {
|
const MAX_PAYLOAD_BYTES: usize = 1_800_000; // 1.8MB (under 2MB API limit)
|
||||||
role: "user".to_string(),
|
|
||||||
content: Some(content.clone()),
|
let mut messages: Vec<OpenAiMessage> = Vec::new();
|
||||||
tool_calls: None,
|
let mut pending_tool_calls: Option<Vec<OpenAiToolCall>> = None;
|
||||||
}),
|
let mut pending_content: Option<String> = None;
|
||||||
zclaw_types::Message::Assistant { content, thinking: _ } => Some(OpenAiMessage {
|
let mut pending_reasoning: Option<String> = None;
|
||||||
|
|
||||||
|
let flush_pending = |tc: &mut Option<Vec<OpenAiToolCall>>,
|
||||||
|
c: &mut Option<String>,
|
||||||
|
r: &mut Option<String>,
|
||||||
|
out: &mut Vec<OpenAiMessage>| {
|
||||||
|
let calls = tc.take();
|
||||||
|
let content = c.take();
|
||||||
|
let reasoning = r.take();
|
||||||
|
|
||||||
|
if let Some(calls) = calls {
|
||||||
|
if !calls.is_empty() {
|
||||||
|
// Merge assistant content + reasoning into the tool call message
|
||||||
|
out.push(OpenAiMessage {
|
||||||
|
role: "assistant".to_string(),
|
||||||
|
content: content.filter(|s| !s.is_empty()),
|
||||||
|
reasoning_content: reasoning.filter(|s| !s.is_empty()),
|
||||||
|
tool_calls: Some(calls),
|
||||||
|
tool_call_id: None,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// No tool calls — emit a plain assistant message
|
||||||
|
if content.is_some() || reasoning.is_some() {
|
||||||
|
out.push(OpenAiMessage {
|
||||||
role: "assistant".to_string(),
|
role: "assistant".to_string(),
|
||||||
content: Some(content.clone()),
|
content: content.filter(|s| !s.is_empty()),
|
||||||
|
reasoning_content: reasoning.filter(|s| !s.is_empty()),
|
||||||
tool_calls: None,
|
tool_calls: None,
|
||||||
}),
|
tool_call_id: None,
|
||||||
zclaw_types::Message::System { content } => Some(OpenAiMessage {
|
});
|
||||||
role: "system".to_string(),
|
}
|
||||||
content: Some(content.clone()),
|
};
|
||||||
tool_calls: None,
|
|
||||||
}),
|
for msg in &request.messages {
|
||||||
|
match msg {
|
||||||
|
zclaw_types::Message::User { content } => {
|
||||||
|
flush_pending(&mut pending_tool_calls, &mut pending_content, &mut pending_reasoning, &mut messages);
|
||||||
|
messages.push(OpenAiMessage {
|
||||||
|
role: "user".to_string(),
|
||||||
|
content: Some(content.clone()),
|
||||||
|
tool_calls: None,
|
||||||
|
tool_call_id: None,
|
||||||
|
reasoning_content: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
zclaw_types::Message::Assistant { content, thinking } => {
|
||||||
|
flush_pending(&mut pending_tool_calls, &mut pending_content, &mut pending_reasoning, &mut messages);
|
||||||
|
// Don't push immediately — wait to see if next messages are ToolUse
|
||||||
|
pending_content = Some(content.clone());
|
||||||
|
pending_reasoning = thinking.clone();
|
||||||
|
}
|
||||||
|
zclaw_types::Message::System { content } => {
|
||||||
|
flush_pending(&mut pending_tool_calls, &mut pending_content, &mut pending_reasoning, &mut messages);
|
||||||
|
messages.push(OpenAiMessage {
|
||||||
|
role: "system".to_string(),
|
||||||
|
content: Some(content.clone()),
|
||||||
|
tool_calls: None,
|
||||||
|
tool_call_id: None,
|
||||||
|
reasoning_content: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
zclaw_types::Message::ToolUse { id, tool, input } => {
|
zclaw_types::Message::ToolUse { id, tool, input } => {
|
||||||
// Ensure arguments is always a valid JSON object, never null or invalid
|
// Accumulate tool calls — they'll be merged with the pending assistant message
|
||||||
let args = if input.is_null() {
|
let args = if input.is_null() {
|
||||||
"{}".to_string()
|
"{}".to_string()
|
||||||
} else {
|
} else {
|
||||||
serde_json::to_string(input).unwrap_or_else(|_| "{}".to_string())
|
serde_json::to_string(input).unwrap_or_else(|_| "{}".to_string())
|
||||||
};
|
};
|
||||||
Some(OpenAiMessage {
|
pending_tool_calls
|
||||||
role: "assistant".to_string(),
|
.get_or_insert_with(Vec::new)
|
||||||
content: None,
|
.push(OpenAiToolCall {
|
||||||
tool_calls: Some(vec![OpenAiToolCall {
|
|
||||||
id: id.clone(),
|
id: id.clone(),
|
||||||
r#type: "function".to_string(),
|
r#type: "function".to_string(),
|
||||||
function: FunctionCall {
|
function: FunctionCall {
|
||||||
name: tool.to_string(),
|
name: tool.to_string(),
|
||||||
arguments: args,
|
arguments: args,
|
||||||
},
|
},
|
||||||
}]),
|
});
|
||||||
})
|
|
||||||
}
|
}
|
||||||
zclaw_types::Message::ToolResult { tool_call_id: _, output, is_error, .. } => Some(OpenAiMessage {
|
zclaw_types::Message::ToolResult { tool_call_id, output, is_error, .. } => {
|
||||||
role: "tool".to_string(),
|
flush_pending(&mut pending_tool_calls, &mut pending_content, &mut pending_reasoning, &mut messages);
|
||||||
content: Some(if *is_error {
|
let content_str = if *is_error {
|
||||||
format!("Error: {}", output)
|
format!("Error: {}", output)
|
||||||
} else {
|
} else {
|
||||||
output.to_string()
|
output.to_string()
|
||||||
}),
|
};
|
||||||
tool_calls: None,
|
// Truncate oversized tool results to prevent payload overflow
|
||||||
}),
|
let truncated = if content_str.len() > MAX_TOOL_RESULT_BYTES {
|
||||||
})
|
let mut s = String::from(&content_str[..MAX_TOOL_RESULT_BYTES]);
|
||||||
.collect();
|
s.push_str("\n\n... [内容已截断,原文过大]");
|
||||||
|
s
|
||||||
|
} else {
|
||||||
|
content_str
|
||||||
|
};
|
||||||
|
messages.push(OpenAiMessage {
|
||||||
|
role: "tool".to_string(),
|
||||||
|
content: Some(truncated),
|
||||||
|
tool_calls: None,
|
||||||
|
tool_call_id: Some(tool_call_id.clone()),
|
||||||
|
reasoning_content: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Flush any remaining accumulated assistant content and/or tool calls
|
||||||
|
flush_pending(&mut pending_tool_calls, &mut pending_content, &mut pending_reasoning, &mut messages);
|
||||||
|
|
||||||
// Add system prompt if provided
|
// Add system prompt if provided
|
||||||
let mut messages = messages;
|
let mut messages = messages;
|
||||||
@@ -361,6 +464,8 @@ impl OpenAiDriver {
|
|||||||
role: "system".to_string(),
|
role: "system".to_string(),
|
||||||
content: Some(system.clone()),
|
content: Some(system.clone()),
|
||||||
tool_calls: None,
|
tool_calls: None,
|
||||||
|
tool_call_id: None,
|
||||||
|
reasoning_content: None,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -376,7 +481,7 @@ impl OpenAiDriver {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
OpenAiRequest {
|
let api_request = OpenAiRequest {
|
||||||
model: request.model.clone(), // Use model ID directly without any transformation
|
model: request.model.clone(), // Use model ID directly without any transformation
|
||||||
messages,
|
messages,
|
||||||
max_tokens: request.max_tokens,
|
max_tokens: request.max_tokens,
|
||||||
@@ -384,7 +489,75 @@ impl OpenAiDriver {
|
|||||||
stop: if request.stop.is_empty() { None } else { Some(request.stop.clone()) },
|
stop: if request.stop.is_empty() { None } else { Some(request.stop.clone()) },
|
||||||
stream: request.stream,
|
stream: request.stream,
|
||||||
tools: if tools.is_empty() { None } else { Some(tools) },
|
tools: if tools.is_empty() { None } else { Some(tools) },
|
||||||
|
};
|
||||||
|
|
||||||
|
// Pre-send payload size validation
|
||||||
|
if let Ok(serialized) = serde_json::to_string(&api_request) {
|
||||||
|
if serialized.len() > MAX_PAYLOAD_BYTES {
|
||||||
|
tracing::warn!(
|
||||||
|
target: "openai_driver",
|
||||||
|
"Request payload too large: {} bytes (limit: {}), truncating messages",
|
||||||
|
serialized.len(),
|
||||||
|
MAX_PAYLOAD_BYTES
|
||||||
|
);
|
||||||
|
return Self::truncate_messages_to_fit(api_request, MAX_PAYLOAD_BYTES);
|
||||||
|
}
|
||||||
|
tracing::debug!(
|
||||||
|
target: "openai_driver",
|
||||||
|
"Request payload size: {} bytes (limit: {})",
|
||||||
|
serialized.len(),
|
||||||
|
MAX_PAYLOAD_BYTES
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
api_request
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emergency truncation: drop oldest non-system messages until payload fits
|
||||||
|
fn truncate_messages_to_fit(mut request: OpenAiRequest, _max_bytes: usize) -> OpenAiRequest {
|
||||||
|
// Keep system message (if any) and last 4 non-system messages
|
||||||
|
let has_system = request.messages.first()
|
||||||
|
.map(|m| m.role == "system")
|
||||||
|
.unwrap_or(false);
|
||||||
|
|
||||||
|
let non_system: Vec<OpenAiMessage> = request.messages.into_iter()
|
||||||
|
.filter(|m| m.role != "system")
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Keep last N messages and truncate any remaining large tool results
|
||||||
|
let keep_count = 4.min(non_system.len());
|
||||||
|
let start = non_system.len() - keep_count;
|
||||||
|
let kept: Vec<OpenAiMessage> = non_system.into_iter()
|
||||||
|
.skip(start)
|
||||||
|
.map(|mut msg| {
|
||||||
|
// Additional per-message truncation for tool results
|
||||||
|
if msg.role == "tool" {
|
||||||
|
if let Some(ref content) = msg.content {
|
||||||
|
if content.len() > 16_384 {
|
||||||
|
let mut s = String::from(&content[..16_384]);
|
||||||
|
s.push_str("\n\n... [上下文压缩截断]");
|
||||||
|
msg.content = Some(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
msg
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut messages = Vec::new();
|
||||||
|
if has_system {
|
||||||
|
messages.push(OpenAiMessage {
|
||||||
|
role: "system".to_string(),
|
||||||
|
content: Some("You are a helpful AI assistant. (注意:对话历史已被压缩以适应上下文大小限制)".to_string()),
|
||||||
|
tool_calls: None,
|
||||||
|
tool_call_id: None,
|
||||||
|
reasoning_content: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
messages.extend(kept);
|
||||||
|
|
||||||
|
request.messages = messages;
|
||||||
|
request
|
||||||
}
|
}
|
||||||
|
|
||||||
fn convert_response(&self, api_response: OpenAiResponse, model: String) -> CompletionResponse {
|
fn convert_response(&self, api_response: OpenAiResponse, model: String) -> CompletionResponse {
|
||||||
@@ -398,6 +571,7 @@ impl OpenAiDriver {
|
|||||||
// This is important because some providers return empty content with tool_calls
|
// This is important because some providers return empty content with tool_calls
|
||||||
let has_tool_calls = c.message.tool_calls.as_ref().map(|tc| !tc.is_empty()).unwrap_or(false);
|
let has_tool_calls = c.message.tool_calls.as_ref().map(|tc| !tc.is_empty()).unwrap_or(false);
|
||||||
let has_content = c.message.content.as_ref().map(|t| !t.is_empty()).unwrap_or(false);
|
let has_content = c.message.content.as_ref().map(|t| !t.is_empty()).unwrap_or(false);
|
||||||
|
let has_reasoning = c.message.reasoning_content.as_ref().map(|t| !t.is_empty()).unwrap_or(false);
|
||||||
|
|
||||||
let blocks = if has_tool_calls {
|
let blocks = if has_tool_calls {
|
||||||
// Tool calls take priority
|
// Tool calls take priority
|
||||||
@@ -413,6 +587,11 @@ impl OpenAiDriver {
|
|||||||
let text = c.message.content.as_ref().unwrap();
|
let text = c.message.content.as_ref().unwrap();
|
||||||
tracing::debug!("[OpenAiDriver:convert_response] Using text content: {} chars", text.len());
|
tracing::debug!("[OpenAiDriver:convert_response] Using text content: {} chars", text.len());
|
||||||
vec![ContentBlock::Text { text: text.clone() }]
|
vec![ContentBlock::Text { text: text.clone() }]
|
||||||
|
} else if has_reasoning {
|
||||||
|
// Content empty but reasoning_content present (Kimi, Qwen, DeepSeek)
|
||||||
|
let reasoning = c.message.reasoning_content.as_ref().unwrap();
|
||||||
|
tracing::debug!("[OpenAiDriver:convert_response] Using reasoning_content: {} chars", reasoning.len());
|
||||||
|
vec![ContentBlock::Text { text: reasoning.clone() }]
|
||||||
} else {
|
} else {
|
||||||
// No content or tool_calls
|
// No content or tool_calls
|
||||||
tracing::debug!("[OpenAiDriver:convert_response] No content or tool_calls, using empty text");
|
tracing::debug!("[OpenAiDriver:convert_response] No content or tool_calls, using empty text");
|
||||||
@@ -594,6 +773,10 @@ struct OpenAiMessage {
|
|||||||
content: Option<String>,
|
content: Option<String>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
tool_calls: Option<Vec<OpenAiToolCall>>,
|
tool_calls: Option<Vec<OpenAiToolCall>>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
tool_call_id: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
reasoning_content: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
@@ -656,6 +839,8 @@ struct OpenAiResponseMessage {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
content: Option<String>,
|
content: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
reasoning_content: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
tool_calls: Option<Vec<OpenAiToolCallResponse>>,
|
tool_calls: Option<Vec<OpenAiToolCallResponse>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -705,6 +890,8 @@ struct OpenAiDelta {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
content: Option<String>,
|
content: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
reasoning_content: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
tool_calls: Option<Vec<OpenAiToolCallDelta>>,
|
tool_calls: Option<Vec<OpenAiToolCallDelta>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,22 +4,14 @@
|
|||||||
//! enabling automatic memory retrieval before conversations and memory extraction
|
//! enabling automatic memory retrieval before conversations and memory extraction
|
||||||
//! after conversations.
|
//! after conversations.
|
||||||
//!
|
//!
|
||||||
//! # Usage
|
//! **Note (2026-03-27 audit)**: In the Tauri desktop deployment, this module is
|
||||||
|
//! NOT wired into the Kernel. The intelligence_hooks module in desktop/src-tauri
|
||||||
|
//! provides the same functionality (memory retrieval, heartbeat, reflection) via
|
||||||
|
//! direct VikingStorage calls. GrowthIntegration remains available for future
|
||||||
|
//! use (e.g., headless/server deployments where intelligence_hooks is not available).
|
||||||
//!
|
//!
|
||||||
//! ```rust,ignore
|
//! The `AgentLoop.growth` field defaults to `None` and the code gracefully falls
|
||||||
//! use zclaw_runtime::growth::GrowthIntegration;
|
//! through to normal behavior when not set.
|
||||||
//! use zclaw_growth::{VikingAdapter, MemoryExtractor, MemoryRetriever, PromptInjector};
|
|
||||||
//!
|
|
||||||
//! // Create growth integration
|
|
||||||
//! let viking = Arc::new(VikingAdapter::in_memory());
|
|
||||||
//! let growth = GrowthIntegration::new(viking);
|
|
||||||
//!
|
|
||||||
//! // Before conversation: enhance system prompt
|
|
||||||
//! let enhanced_prompt = growth.enhance_prompt(&agent_id, &base_prompt, &user_input).await?;
|
|
||||||
//!
|
|
||||||
//! // After conversation: extract and store memories
|
|
||||||
//! growth.process_conversation(&agent_id, &messages, session_id).await?;
|
|
||||||
//! ```
|
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use zclaw_growth::{
|
use zclaw_growth::{
|
||||||
|
|||||||
@@ -3,8 +3,10 @@
|
|||||||
//! LLM drivers, tool system, and agent loop implementation.
|
//! LLM drivers, tool system, and agent loop implementation.
|
||||||
|
|
||||||
/// Default User-Agent header sent with all outgoing HTTP requests.
|
/// Default User-Agent header sent with all outgoing HTTP requests.
|
||||||
/// Some LLM providers (e.g. Moonshot, Qwen, DashScope Coding Plan) reject requests without one.
|
/// Coding Plan providers (Kimi, Bailian/DashScope, Zhipu) validate the User-Agent against a
|
||||||
pub const USER_AGENT: &str = "ZCLAW/0.1.0";
|
/// whitelist of known Coding Agents (e.g. claude-code, kimi-cli, roo-code, kilo-code).
|
||||||
|
/// Must use the exact lowercase format to pass validation.
|
||||||
|
pub const USER_AGENT: &str = "claude-code/0.1.0";
|
||||||
|
|
||||||
pub mod driver;
|
pub mod driver;
|
||||||
pub mod tool;
|
pub mod tool;
|
||||||
|
|||||||
@@ -131,12 +131,30 @@ impl AgentLoop {
|
|||||||
|
|
||||||
/// Create tool context for tool execution
|
/// Create tool context for tool execution
|
||||||
fn create_tool_context(&self, session_id: SessionId) -> ToolContext {
|
fn create_tool_context(&self, session_id: SessionId) -> ToolContext {
|
||||||
|
// If no path_validator is configured, create a default one with user home as workspace.
|
||||||
|
// This allows file_read/file_write tools to work without explicit workspace config,
|
||||||
|
// while still restricting access to the user's home directory for security.
|
||||||
|
let path_validator = self.path_validator.clone().unwrap_or_else(|| {
|
||||||
|
let home = std::env::var("USERPROFILE")
|
||||||
|
.or_else(|_| std::env::var("HOME"))
|
||||||
|
.unwrap_or_else(|_| ".".to_string());
|
||||||
|
let home_path = std::path::PathBuf::from(&home);
|
||||||
|
tracing::info!(
|
||||||
|
"[AgentLoop] No path_validator configured, using user home as workspace: {}",
|
||||||
|
home_path.display()
|
||||||
|
);
|
||||||
|
PathValidator::new().with_workspace(home_path)
|
||||||
|
});
|
||||||
|
|
||||||
|
let working_dir = path_validator.workspace_root()
|
||||||
|
.map(|p| p.to_string_lossy().to_string());
|
||||||
|
|
||||||
ToolContext {
|
ToolContext {
|
||||||
agent_id: self.agent_id.clone(),
|
agent_id: self.agent_id.clone(),
|
||||||
working_directory: None,
|
working_directory: working_dir,
|
||||||
session_id: Some(session_id.to_string()),
|
session_id: Some(session_id.to_string()),
|
||||||
skill_executor: self.skill_executor.clone(),
|
skill_executor: self.skill_executor.clone(),
|
||||||
path_validator: self.path_validator.clone(),
|
path_validator: Some(path_validator),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,6 +240,14 @@ impl AgentLoop {
|
|||||||
total_input_tokens += response.input_tokens;
|
total_input_tokens += response.input_tokens;
|
||||||
total_output_tokens += response.output_tokens;
|
total_output_tokens += response.output_tokens;
|
||||||
|
|
||||||
|
// Calibrate token estimation on first iteration
|
||||||
|
if iterations == 1 {
|
||||||
|
compaction::update_calibration(
|
||||||
|
compaction::estimate_messages_tokens(&messages),
|
||||||
|
response.input_tokens,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Extract tool calls from response
|
// Extract tool calls from response
|
||||||
let tool_calls: Vec<(String, String, serde_json::Value)> = response.content.iter()
|
let tool_calls: Vec<(String, String, serde_json::Value)> = response.content.iter()
|
||||||
.filter_map(|block| match block {
|
.filter_map(|block| match block {
|
||||||
@@ -230,30 +256,49 @@ impl AgentLoop {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
// Extract text and thinking separately
|
||||||
|
let text_parts: Vec<String> = response.content.iter()
|
||||||
|
.filter_map(|block| match block {
|
||||||
|
ContentBlock::Text { text } => Some(text.clone()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let thinking_parts: Vec<String> = response.content.iter()
|
||||||
|
.filter_map(|block| match block {
|
||||||
|
ContentBlock::Thinking { thinking } => Some(thinking.clone()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let text_content = text_parts.join("\n");
|
||||||
|
let thinking_content = if thinking_parts.is_empty() { None } else { Some(thinking_parts.join("")) };
|
||||||
|
|
||||||
// If no tool calls, we have the final response
|
// If no tool calls, we have the final response
|
||||||
if tool_calls.is_empty() {
|
if tool_calls.is_empty() {
|
||||||
// Extract text content
|
// Save final assistant message with thinking
|
||||||
let text = response.content.iter()
|
let msg = if let Some(thinking) = &thinking_content {
|
||||||
.filter_map(|block| match block {
|
Message::assistant_with_thinking(&text_content, thinking)
|
||||||
ContentBlock::Text { text } => Some(text.clone()),
|
} else {
|
||||||
ContentBlock::Thinking { thinking } => Some(format!("[思考] {}", thinking)),
|
Message::assistant(&text_content)
|
||||||
_ => None,
|
};
|
||||||
})
|
self.memory.append_message(&session_id, &msg).await?;
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
|
|
||||||
// Save final assistant message
|
|
||||||
self.memory.append_message(&session_id, &Message::assistant(&text)).await?;
|
|
||||||
|
|
||||||
break AgentLoopResult {
|
break AgentLoopResult {
|
||||||
response: text,
|
response: text_content,
|
||||||
input_tokens: total_input_tokens,
|
input_tokens: total_input_tokens,
|
||||||
output_tokens: total_output_tokens,
|
output_tokens: total_output_tokens,
|
||||||
iterations,
|
iterations,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// There are tool calls - add assistant message with tool calls to history
|
// There are tool calls - push assistant message with thinking before tool calls
|
||||||
|
// (required by Kimi and other thinking-enabled APIs)
|
||||||
|
let assistant_msg = if let Some(thinking) = &thinking_content {
|
||||||
|
Message::assistant_with_thinking(&text_content, thinking)
|
||||||
|
} else {
|
||||||
|
Message::assistant(&text_content)
|
||||||
|
};
|
||||||
|
messages.push(assistant_msg);
|
||||||
|
|
||||||
for (id, name, input) in &tool_calls {
|
for (id, name, input) in &tool_calls {
|
||||||
messages.push(Message::tool_use(id, zclaw_types::ToolId::new(name), input.clone()));
|
messages.push(Message::tool_use(id, zclaw_types::ToolId::new(name), input.clone()));
|
||||||
}
|
}
|
||||||
@@ -417,19 +462,29 @@ impl AgentLoop {
|
|||||||
let mut stream = driver.stream(request);
|
let mut stream = driver.stream(request);
|
||||||
let mut pending_tool_calls: Vec<(String, String, serde_json::Value)> = Vec::new();
|
let mut pending_tool_calls: Vec<(String, String, serde_json::Value)> = Vec::new();
|
||||||
let mut iteration_text = String::new();
|
let mut iteration_text = String::new();
|
||||||
|
let mut reasoning_text = String::new(); // Track reasoning separately for API requirement
|
||||||
|
|
||||||
// Process stream chunks
|
// Process stream chunks
|
||||||
tracing::debug!("[AgentLoop] Starting to process stream chunks");
|
tracing::debug!("[AgentLoop] Starting to process stream chunks");
|
||||||
|
let mut chunk_count: usize = 0;
|
||||||
|
let mut text_delta_count: usize = 0;
|
||||||
|
let mut thinking_delta_count: usize = 0;
|
||||||
while let Some(chunk_result) = stream.next().await {
|
while let Some(chunk_result) = stream.next().await {
|
||||||
match chunk_result {
|
match chunk_result {
|
||||||
Ok(chunk) => {
|
Ok(chunk) => {
|
||||||
|
chunk_count += 1;
|
||||||
match &chunk {
|
match &chunk {
|
||||||
StreamChunk::TextDelta { delta } => {
|
StreamChunk::TextDelta { delta } => {
|
||||||
|
text_delta_count += 1;
|
||||||
|
tracing::debug!("[AgentLoop] TextDelta #{}: {} chars", text_delta_count, delta.len());
|
||||||
iteration_text.push_str(delta);
|
iteration_text.push_str(delta);
|
||||||
let _ = tx.send(LoopEvent::Delta(delta.clone())).await;
|
let _ = tx.send(LoopEvent::Delta(delta.clone())).await;
|
||||||
}
|
}
|
||||||
StreamChunk::ThinkingDelta { delta } => {
|
StreamChunk::ThinkingDelta { delta } => {
|
||||||
let _ = tx.send(LoopEvent::Delta(format!("[思考] {}", delta))).await;
|
thinking_delta_count += 1;
|
||||||
|
tracing::debug!("[AgentLoop] ThinkingDelta #{}: {} chars", thinking_delta_count, delta.len());
|
||||||
|
// Accumulate reasoning separately — not mixed into iteration_text
|
||||||
|
reasoning_text.push_str(delta);
|
||||||
}
|
}
|
||||||
StreamChunk::ToolUseStart { id, name } => {
|
StreamChunk::ToolUseStart { id, name } => {
|
||||||
tracing::debug!("[AgentLoop] ToolUseStart: id={}, name={}", id, name);
|
tracing::debug!("[AgentLoop] ToolUseStart: id={}, name={}", id, name);
|
||||||
@@ -458,6 +513,13 @@ impl AgentLoop {
|
|||||||
tracing::debug!("[AgentLoop] Stream complete: input_tokens={}, output_tokens={}", it, ot);
|
tracing::debug!("[AgentLoop] Stream complete: input_tokens={}, output_tokens={}", it, ot);
|
||||||
total_input_tokens += *it;
|
total_input_tokens += *it;
|
||||||
total_output_tokens += *ot;
|
total_output_tokens += *ot;
|
||||||
|
// Calibrate token estimation on first iteration
|
||||||
|
if iteration == 1 {
|
||||||
|
compaction::update_calibration(
|
||||||
|
compaction::estimate_messages_tokens(&messages),
|
||||||
|
*it,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
StreamChunk::Error { message } => {
|
StreamChunk::Error { message } => {
|
||||||
tracing::error!("[AgentLoop] Stream error: {}", message);
|
tracing::error!("[AgentLoop] Stream error: {}", message);
|
||||||
@@ -471,16 +533,27 @@ impl AgentLoop {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tracing::debug!("[AgentLoop] Stream ended, pending_tool_calls count: {}", pending_tool_calls.len());
|
tracing::info!("[AgentLoop] Stream ended: {} total chunks (text={}, thinking={}, tools={}), iteration_text={} chars",
|
||||||
|
chunk_count, text_delta_count, thinking_delta_count, pending_tool_calls.len(),
|
||||||
|
iteration_text.len());
|
||||||
|
if iteration_text.is_empty() {
|
||||||
|
tracing::warn!("[AgentLoop] WARNING: iteration_text is EMPTY after {} chunks! text_delta={}, thinking_delta={}",
|
||||||
|
chunk_count, text_delta_count, thinking_delta_count);
|
||||||
|
}
|
||||||
|
|
||||||
// If no tool calls, we have the final response
|
// If no tool calls, we have the final response
|
||||||
if pending_tool_calls.is_empty() {
|
if pending_tool_calls.is_empty() {
|
||||||
tracing::debug!("[AgentLoop] No tool calls, returning final response");
|
tracing::info!("[AgentLoop] No tool calls, returning final response: {} chars (reasoning: {} chars)", iteration_text.len(), reasoning_text.len());
|
||||||
// Save final assistant message
|
// Save final assistant message with reasoning
|
||||||
let _ = memory.append_message(&session_id_clone, &Message::assistant(&iteration_text)).await;
|
if let Err(e) = memory.append_message(&session_id_clone, &Message::assistant_with_thinking(
|
||||||
|
&iteration_text,
|
||||||
|
&reasoning_text,
|
||||||
|
)).await {
|
||||||
|
tracing::warn!("[AgentLoop] Failed to save final assistant message: {}", e);
|
||||||
|
}
|
||||||
|
|
||||||
let _ = tx.send(LoopEvent::Complete(AgentLoopResult {
|
let _ = tx.send(LoopEvent::Complete(AgentLoopResult {
|
||||||
response: iteration_text,
|
response: iteration_text.clone(),
|
||||||
input_tokens: total_input_tokens,
|
input_tokens: total_input_tokens,
|
||||||
output_tokens: total_output_tokens,
|
output_tokens: total_output_tokens,
|
||||||
iterations: iteration,
|
iterations: iteration,
|
||||||
@@ -488,7 +561,13 @@ impl AgentLoop {
|
|||||||
break 'outer;
|
break 'outer;
|
||||||
}
|
}
|
||||||
|
|
||||||
tracing::debug!("[AgentLoop] Processing {} tool calls", pending_tool_calls.len());
|
tracing::debug!("[AgentLoop] Processing {} tool calls (reasoning: {} chars)", pending_tool_calls.len(), reasoning_text.len());
|
||||||
|
|
||||||
|
// Push assistant message with reasoning before tool calls (required by Kimi and other thinking-enabled APIs)
|
||||||
|
messages.push(Message::assistant_with_thinking(
|
||||||
|
&iteration_text,
|
||||||
|
&reasoning_text,
|
||||||
|
));
|
||||||
|
|
||||||
// There are tool calls - add to message history
|
// There are tool calls - add to message history
|
||||||
for (id, name, input) in &pending_tool_calls {
|
for (id, name, input) in &pending_tool_calls {
|
||||||
@@ -519,12 +598,21 @@ impl AgentLoop {
|
|||||||
}
|
}
|
||||||
LoopGuardResult::Allowed => {}
|
LoopGuardResult::Allowed => {}
|
||||||
}
|
}
|
||||||
|
// Use pre-resolved path_validator (already has default fallback from create_tool_context logic)
|
||||||
|
let pv = path_validator.clone().unwrap_or_else(|| {
|
||||||
|
let home = std::env::var("USERPROFILE")
|
||||||
|
.or_else(|_| std::env::var("HOME"))
|
||||||
|
.unwrap_or_else(|_| ".".to_string());
|
||||||
|
PathValidator::new().with_workspace(std::path::PathBuf::from(&home))
|
||||||
|
});
|
||||||
|
let working_dir = pv.workspace_root()
|
||||||
|
.map(|p| p.to_string_lossy().to_string());
|
||||||
let tool_context = ToolContext {
|
let tool_context = ToolContext {
|
||||||
agent_id: agent_id.clone(),
|
agent_id: agent_id.clone(),
|
||||||
working_directory: None,
|
working_directory: working_dir,
|
||||||
session_id: Some(session_id_clone.to_string()),
|
session_id: Some(session_id_clone.to_string()),
|
||||||
skill_executor: skill_executor.clone(),
|
skill_executor: skill_executor.clone(),
|
||||||
path_validator: path_validator.clone(),
|
path_validator: Some(pv),
|
||||||
};
|
};
|
||||||
|
|
||||||
let (result, is_error) = if let Some(tool) = tools.get(&name) {
|
let (result, is_error) = if let Some(tool) = tools.get(&name) {
|
||||||
|
|||||||
@@ -160,6 +160,11 @@ impl PathValidator {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the workspace root directory
|
||||||
|
pub fn workspace_root(&self) -> Option<&PathBuf> {
|
||||||
|
self.workspace_root.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
/// Validate a path for read access
|
/// Validate a path for read access
|
||||||
pub fn validate_read(&self, path: &str) -> Result<PathBuf> {
|
pub fn validate_read(&self, path: &str) -> Result<PathBuf> {
|
||||||
let canonical = self.resolve_and_validate(path)?;
|
let canonical = self.resolve_and_validate(path)?;
|
||||||
|
|||||||
50
crates/zclaw-saas/Cargo.toml
Normal file
50
crates/zclaw-saas/Cargo.toml
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
[package]
|
||||||
|
name = "zclaw-saas"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
description = "ZCLAW SaaS backend - account, API config, relay, migration"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "zclaw-saas"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
zclaw-types = { workspace = true }
|
||||||
|
|
||||||
|
tokio = { workspace = true }
|
||||||
|
tokio-stream = { workspace = true }
|
||||||
|
futures = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
toml = { workspace = true }
|
||||||
|
thiserror = { workspace = true }
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
|
chrono = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
|
tracing-subscriber = { workspace = true }
|
||||||
|
sqlx = { workspace = true }
|
||||||
|
reqwest = { workspace = true }
|
||||||
|
secrecy = { workspace = true }
|
||||||
|
sha2 = { workspace = true }
|
||||||
|
rand = { workspace = true }
|
||||||
|
dashmap = { workspace = true }
|
||||||
|
hex = { workspace = true }
|
||||||
|
url = "2"
|
||||||
|
|
||||||
|
axum = { workspace = true }
|
||||||
|
axum-extra = { workspace = true }
|
||||||
|
tower = { workspace = true }
|
||||||
|
tower-http = { workspace = true }
|
||||||
|
jsonwebtoken = { workspace = true }
|
||||||
|
argon2 = { workspace = true }
|
||||||
|
totp-rs = { workspace = true }
|
||||||
|
urlencoding = "2"
|
||||||
|
data-encoding = "2"
|
||||||
|
regex = "1"
|
||||||
|
aes-gcm = "0.10"
|
||||||
|
bytes = "1"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = { workspace = true }
|
||||||
336
crates/zclaw-saas/migrations/20260329000001_initial_schema.sql
Normal file
336
crates/zclaw-saas/migrations/20260329000001_initial_schema.sql
Normal file
@@ -0,0 +1,336 @@
|
|||||||
|
-- Migration: Initial schema with TIMESTAMPTZ
|
||||||
|
-- Extracted from inline SCHEMA_SQL in db.rs, with TEXT timestamps converted to TIMESTAMPTZ.
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS saas_schema_version (
|
||||||
|
version INTEGER PRIMARY KEY
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS accounts (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL UNIQUE,
|
||||||
|
email TEXT NOT NULL UNIQUE,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
display_name TEXT NOT NULL DEFAULT '',
|
||||||
|
avatar_url TEXT,
|
||||||
|
role TEXT NOT NULL DEFAULT 'user',
|
||||||
|
status TEXT NOT NULL DEFAULT 'active',
|
||||||
|
totp_secret TEXT,
|
||||||
|
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
last_login_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_accounts_email ON accounts(email);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_accounts_role ON accounts(role);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS api_tokens (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
token_hash TEXT NOT NULL,
|
||||||
|
token_prefix TEXT NOT NULL,
|
||||||
|
permissions TEXT NOT NULL DEFAULT '[]',
|
||||||
|
last_used_at TIMESTAMPTZ,
|
||||||
|
expires_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
revoked_at TIMESTAMPTZ,
|
||||||
|
FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_api_tokens_account ON api_tokens(account_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_api_tokens_hash ON api_tokens(token_hash);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS roles (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
permissions TEXT NOT NULL DEFAULT '[]',
|
||||||
|
is_system BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS permission_templates (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
permissions TEXT NOT NULL DEFAULT '[]',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS operation_logs (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
account_id TEXT,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
target_type TEXT,
|
||||||
|
target_id TEXT,
|
||||||
|
details TEXT,
|
||||||
|
ip_address TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_op_logs_account ON operation_logs(account_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_op_logs_action ON operation_logs(action);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_op_logs_time ON operation_logs(created_at);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS providers (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL UNIQUE,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
api_key TEXT,
|
||||||
|
base_url TEXT NOT NULL,
|
||||||
|
api_protocol TEXT NOT NULL DEFAULT 'openai',
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
rate_limit_rpm INTEGER,
|
||||||
|
rate_limit_tpm INTEGER,
|
||||||
|
config_json TEXT DEFAULT '{}',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS models (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
provider_id TEXT NOT NULL,
|
||||||
|
model_id TEXT NOT NULL,
|
||||||
|
alias TEXT NOT NULL,
|
||||||
|
context_window BIGINT NOT NULL DEFAULT 8192,
|
||||||
|
max_output_tokens BIGINT NOT NULL DEFAULT 4096,
|
||||||
|
supports_streaming BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
supports_vision BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
pricing_input DOUBLE PRECISION DEFAULT 0,
|
||||||
|
pricing_output DOUBLE PRECISION DEFAULT 0,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE(provider_id, model_id),
|
||||||
|
FOREIGN KEY (provider_id) REFERENCES providers(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_models_provider ON models(provider_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS account_api_keys (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
provider_id TEXT NOT NULL,
|
||||||
|
key_value TEXT NOT NULL,
|
||||||
|
key_label TEXT,
|
||||||
|
permissions TEXT NOT NULL DEFAULT '[]',
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
last_used_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
revoked_at TIMESTAMPTZ,
|
||||||
|
FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY (provider_id) REFERENCES providers(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_account_api_keys_account ON account_api_keys(account_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS usage_records (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
provider_id TEXT NOT NULL,
|
||||||
|
model_id TEXT NOT NULL,
|
||||||
|
input_tokens INTEGER NOT NULL DEFAULT 0,
|
||||||
|
output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||||
|
latency_ms INTEGER,
|
||||||
|
status TEXT NOT NULL DEFAULT 'success',
|
||||||
|
error_message TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_usage_account ON usage_records(account_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_usage_time ON usage_records(created_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_usage_day ON usage_records((created_at::date));
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS relay_tasks (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
provider_id TEXT NOT NULL,
|
||||||
|
model_id TEXT NOT NULL,
|
||||||
|
request_hash TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued',
|
||||||
|
priority INTEGER NOT NULL DEFAULT 0,
|
||||||
|
attempt_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
max_attempts INTEGER NOT NULL DEFAULT 3,
|
||||||
|
request_body TEXT NOT NULL,
|
||||||
|
response_body TEXT,
|
||||||
|
input_tokens INTEGER DEFAULT 0,
|
||||||
|
output_tokens INTEGER DEFAULT 0,
|
||||||
|
error_message TEXT,
|
||||||
|
queued_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
started_at TIMESTAMPTZ,
|
||||||
|
completed_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_relay_status ON relay_tasks(status);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_relay_account ON relay_tasks(account_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_relay_provider ON relay_tasks(provider_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_relay_time ON relay_tasks(created_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_relay_day ON relay_tasks((created_at::date));
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS config_items (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
category TEXT NOT NULL,
|
||||||
|
key_path TEXT NOT NULL,
|
||||||
|
value_type TEXT NOT NULL,
|
||||||
|
current_value TEXT,
|
||||||
|
default_value TEXT,
|
||||||
|
source TEXT NOT NULL DEFAULT 'local',
|
||||||
|
description TEXT,
|
||||||
|
requires_restart BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE(category, key_path)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_config_category ON config_items(category);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS config_sync_log (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
client_fingerprint TEXT NOT NULL,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
config_keys TEXT NOT NULL,
|
||||||
|
client_values TEXT,
|
||||||
|
saas_values TEXT,
|
||||||
|
resolution TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sync_account ON config_sync_log(account_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS devices (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
device_id TEXT NOT NULL,
|
||||||
|
device_name TEXT,
|
||||||
|
platform TEXT,
|
||||||
|
app_version TEXT,
|
||||||
|
last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_devices_account ON devices(account_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_devices_device_id ON devices(device_id);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_devices_unique ON devices(account_id, device_id);
|
||||||
|
|
||||||
|
-- Prompt template master table
|
||||||
|
CREATE TABLE IF NOT EXISTS prompt_templates (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL UNIQUE,
|
||||||
|
category TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
source TEXT NOT NULL DEFAULT 'builtin',
|
||||||
|
current_version INTEGER NOT NULL DEFAULT 1,
|
||||||
|
status TEXT NOT NULL DEFAULT 'active',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_prompt_status ON prompt_templates(status);
|
||||||
|
|
||||||
|
-- Prompt versions table (immutable)
|
||||||
|
CREATE TABLE IF NOT EXISTS prompt_versions (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
template_id TEXT NOT NULL,
|
||||||
|
version INTEGER NOT NULL,
|
||||||
|
system_prompt TEXT,
|
||||||
|
user_prompt_template TEXT,
|
||||||
|
variables TEXT NOT NULL DEFAULT '[]',
|
||||||
|
changelog TEXT,
|
||||||
|
min_app_version TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE(template_id, version)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_prompt_ver_template ON prompt_versions(template_id);
|
||||||
|
|
||||||
|
-- Client prompt sync status
|
||||||
|
CREATE TABLE IF NOT EXISTS prompt_sync_status (
|
||||||
|
device_id TEXT NOT NULL,
|
||||||
|
template_id TEXT NOT NULL,
|
||||||
|
synced_version INTEGER NOT NULL,
|
||||||
|
synced_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
PRIMARY KEY(device_id, template_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Provider Key Pool table
|
||||||
|
CREATE TABLE IF NOT EXISTS provider_keys (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
provider_id TEXT NOT NULL,
|
||||||
|
key_label TEXT NOT NULL,
|
||||||
|
key_value TEXT NOT NULL,
|
||||||
|
priority INTEGER NOT NULL DEFAULT 0,
|
||||||
|
max_rpm INTEGER,
|
||||||
|
max_tpm INTEGER,
|
||||||
|
quota_reset_interval TEXT,
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
last_429_at TIMESTAMPTZ,
|
||||||
|
cooldown_until TIMESTAMPTZ,
|
||||||
|
total_requests BIGINT NOT NULL DEFAULT 0,
|
||||||
|
total_tokens BIGINT NOT NULL DEFAULT 0,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_pkeys_provider ON provider_keys(provider_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_pkeys_active ON provider_keys(provider_id, is_active);
|
||||||
|
|
||||||
|
-- Key usage sliding window
|
||||||
|
CREATE TABLE IF NOT EXISTS key_usage_window (
|
||||||
|
key_id TEXT NOT NULL,
|
||||||
|
window_minute TEXT NOT NULL,
|
||||||
|
request_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
token_count BIGINT NOT NULL DEFAULT 0,
|
||||||
|
PRIMARY KEY(key_id, window_minute)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Agent config template table
|
||||||
|
CREATE TABLE IF NOT EXISTS agent_templates (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
category TEXT NOT NULL DEFAULT 'general',
|
||||||
|
source TEXT NOT NULL DEFAULT 'builtin',
|
||||||
|
model TEXT,
|
||||||
|
system_prompt TEXT,
|
||||||
|
tools TEXT NOT NULL DEFAULT '[]'::text,
|
||||||
|
capabilities TEXT NOT NULL DEFAULT '[]'::text,
|
||||||
|
temperature DOUBLE PRECISION,
|
||||||
|
max_tokens INTEGER,
|
||||||
|
visibility TEXT NOT NULL DEFAULT 'public',
|
||||||
|
status TEXT NOT NULL DEFAULT 'active',
|
||||||
|
current_version INTEGER NOT NULL DEFAULT 1,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_agent_tmpl_status ON agent_templates(status);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_agent_tmpl_visibility ON agent_templates(visibility);
|
||||||
|
|
||||||
|
-- Desktop telemetry report table (token usage statistics, no content)
|
||||||
|
CREATE TABLE IF NOT EXISTS telemetry_reports (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
device_id TEXT NOT NULL,
|
||||||
|
app_version TEXT,
|
||||||
|
model_id TEXT NOT NULL,
|
||||||
|
input_tokens BIGINT NOT NULL DEFAULT 0,
|
||||||
|
output_tokens BIGINT NOT NULL DEFAULT 0,
|
||||||
|
latency_ms INTEGER,
|
||||||
|
success BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
error_type TEXT,
|
||||||
|
connection_mode TEXT NOT NULL DEFAULT 'tauri',
|
||||||
|
reported_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_telemetry_account ON telemetry_reports(account_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_telemetry_time ON telemetry_reports(reported_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_telemetry_model ON telemetry_reports(model_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_telemetry_day ON telemetry_reports((reported_at::date));
|
||||||
|
|
||||||
|
-- Refresh Token storage (single-use, JWT jti tracking)
|
||||||
|
CREATE TABLE IF NOT EXISTS refresh_tokens (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
jti TEXT NOT NULL UNIQUE,
|
||||||
|
token_hash TEXT NOT NULL,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
used_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_refresh_account ON refresh_tokens(account_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_refresh_jti ON refresh_tokens(jti);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_refresh_expires ON refresh_tokens(expires_at);
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- Migration: Seed roles (super_admin, admin, user)
|
||||||
|
-- Timestamps use NOW() to match TIMESTAMPTZ columns from initial schema.
|
||||||
|
|
||||||
|
INSERT INTO roles (id, name, description, permissions, is_system, created_at, updated_at)
|
||||||
|
VALUES
|
||||||
|
('super_admin', '超级管理员', '拥有所有权限', '["admin:full","account:admin","provider:manage","model:manage","relay:admin","config:write","prompt:read","prompt:write","prompt:publish","prompt:admin"]', TRUE, NOW(), NOW()),
|
||||||
|
('admin', '管理员', '管理账号和配置', '["account:read","account:admin","provider:manage","model:read","model:manage","relay:use","relay:admin","config:read","config:write","prompt:read","prompt:write","prompt:publish"]', TRUE, NOW(), NOW()),
|
||||||
|
('user', '普通用户', '基础使用权限', '["model:read","relay:use","config:read","prompt:read"]', TRUE, NOW(), NOW())
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
310
crates/zclaw-saas/src/account/handlers.rs
Normal file
310
crates/zclaw-saas/src/account/handlers.rs
Normal file
@@ -0,0 +1,310 @@
|
|||||||
|
//! 账号管理 HTTP 处理器
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
extract::{Extension, Path, Query, State},
|
||||||
|
Json,
|
||||||
|
};
|
||||||
|
use crate::state::AppState;
|
||||||
|
use crate::error::{SaasError, SaasResult};
|
||||||
|
use crate::auth::types::AuthContext;
|
||||||
|
use crate::auth::handlers::{log_operation, check_permission};
|
||||||
|
use crate::models::{OperationLogRow, DashboardStatsRow, DashboardTodayRow};
|
||||||
|
use super::{types::*, service};
|
||||||
|
|
||||||
|
fn require_admin(ctx: &AuthContext) -> SaasResult<()> {
|
||||||
|
check_permission(ctx, "account:admin")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/accounts (admin only)
|
||||||
|
pub async fn list_accounts(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Query(query): Query<ListAccountsQuery>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<PaginatedResponse<serde_json::Value>>> {
|
||||||
|
require_admin(&ctx)?;
|
||||||
|
service::list_accounts(&state.db, &query).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/accounts/:id
|
||||||
|
pub async fn get_account(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
// 只能查看自己,或 admin 查看任何人
|
||||||
|
if id != ctx.account_id {
|
||||||
|
require_admin(&ctx)?;
|
||||||
|
}
|
||||||
|
service::get_account(&state.db, &id).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// PATCH /api/v1/accounts/:id (admin or self for limited fields)
|
||||||
|
pub async fn update_account(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<UpdateAccountRequest>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
let is_self_update = id == ctx.account_id;
|
||||||
|
|
||||||
|
// 非管理员只能修改自己的资料
|
||||||
|
if !is_self_update {
|
||||||
|
require_admin(&ctx)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 安全限制: 非管理员修改自己时,剥离 role 字段防止自角色提升
|
||||||
|
let safe_req = if is_self_update && !ctx.permissions.contains(&"admin:full".to_string()) {
|
||||||
|
UpdateAccountRequest {
|
||||||
|
role: None,
|
||||||
|
..req
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
req
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = service::update_account(&state.db, &id, &safe_req).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "account.update", "account", &id, None, ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// PATCH /api/v1/accounts/:id/status (admin only)
|
||||||
|
pub async fn update_status(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<UpdateStatusRequest>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
require_admin(&ctx)?;
|
||||||
|
service::update_account_status(&state.db, &id, &req.status).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "account.update_status", "account", &id,
|
||||||
|
Some(serde_json::json!({"status": &req.status})), ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(serde_json::json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/tokens?page=1&page_size=20
|
||||||
|
pub async fn list_tokens(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Query(params): Query<std::collections::HashMap<String, String>>,
|
||||||
|
) -> SaasResult<Json<PaginatedResponse<TokenInfo>>> {
|
||||||
|
let page = params.get("page").and_then(|v| v.parse().ok());
|
||||||
|
let page_size = params.get("page_size").and_then(|v| v.parse().ok());
|
||||||
|
service::list_api_tokens(&state.db, &ctx.account_id, page, page_size).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/tokens
|
||||||
|
pub async fn create_token(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<CreateTokenRequest>,
|
||||||
|
) -> SaasResult<Json<TokenInfo>> {
|
||||||
|
// 权限校验: 创建的 token 不能超出创建者已有的权限
|
||||||
|
let allowed_permissions: Vec<String> = req.permissions
|
||||||
|
.into_iter()
|
||||||
|
.filter(|p| ctx.permissions.contains(p))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if allowed_permissions.is_empty() {
|
||||||
|
return Err(SaasError::InvalidInput("请求的权限均不被允许".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let filtered_req = CreateTokenRequest {
|
||||||
|
name: req.name,
|
||||||
|
permissions: allowed_permissions,
|
||||||
|
expires_days: req.expires_days,
|
||||||
|
};
|
||||||
|
let token = service::create_api_token(&state.db, &ctx.account_id, &filtered_req).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "token.create", "api_token", &token.id,
|
||||||
|
Some(serde_json::json!({"name": &filtered_req.name})), ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(token))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// DELETE /api/v1/tokens/:id
|
||||||
|
pub async fn revoke_token(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
service::revoke_api_token(&state.db, &id, &ctx.account_id).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "token.revoke", "api_token", &id, None, ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(serde_json::json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/logs/operations (admin only)
|
||||||
|
pub async fn list_operation_logs(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Query(params): Query<std::collections::HashMap<String, String>>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<PaginatedResponse<serde_json::Value>>> {
|
||||||
|
require_admin(&ctx)?;
|
||||||
|
let page: u32 = params.get("page").and_then(|v| v.parse().ok()).unwrap_or(1).max(1);
|
||||||
|
let page_size: u32 = params.get("page_size").and_then(|v| v.parse().ok()).unwrap_or(50).min(100);
|
||||||
|
let offset = ((page - 1) * page_size) as i64;
|
||||||
|
|
||||||
|
let total: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM operation_logs")
|
||||||
|
.fetch_one(&state.db).await?;
|
||||||
|
|
||||||
|
let rows: Vec<OperationLogRow> =
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, account_id, action, target_type, target_id, details, ip_address, created_at
|
||||||
|
FROM operation_logs ORDER BY created_at DESC LIMIT $1 OFFSET $2"
|
||||||
|
)
|
||||||
|
.bind(page_size as i64)
|
||||||
|
.bind(offset)
|
||||||
|
.fetch_all(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let items: Vec<serde_json::Value> = rows.into_iter().map(|r| {
|
||||||
|
serde_json::json!({
|
||||||
|
"id": r.id, "account_id": r.account_id, "action": r.action,
|
||||||
|
"target_type": r.target_type, "target_id": r.target_id,
|
||||||
|
"details": r.details.and_then(|d| serde_json::from_str::<serde_json::Value>(&d).ok()),
|
||||||
|
"ip_address": r.ip_address, "created_at": r.created_at,
|
||||||
|
})
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
Ok(Json(PaginatedResponse { items, total, page, page_size }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/stats/dashboard — 仪表盘聚合统计 (需要 admin 权限)
|
||||||
|
pub async fn dashboard_stats(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
require_admin(&ctx)?;
|
||||||
|
|
||||||
|
// 查询 1: 账号 + Provider + Model 聚合 (一次查询)
|
||||||
|
let stats_row: DashboardStatsRow = sqlx::query_as(
|
||||||
|
"SELECT
|
||||||
|
(SELECT COUNT(*) FROM accounts) as total_accounts,
|
||||||
|
(SELECT COUNT(*) FROM accounts WHERE status = 'active') as active_accounts,
|
||||||
|
(SELECT COUNT(*) FROM providers WHERE enabled = true) as active_providers,
|
||||||
|
(SELECT COUNT(*) FROM models WHERE enabled = true) as active_models"
|
||||||
|
).fetch_one(&state.db).await?;
|
||||||
|
|
||||||
|
// 查询 2: 今日中转统计 — 使用范围查询走 B-tree 索引
|
||||||
|
let today_start = chrono::Utc::now()
|
||||||
|
.date_naive()
|
||||||
|
.and_hms_opt(0, 0, 0).unwrap()
|
||||||
|
.and_utc()
|
||||||
|
.to_rfc3339();
|
||||||
|
let tomorrow_start = (chrono::Utc::now() + chrono::Duration::days(1))
|
||||||
|
.date_naive()
|
||||||
|
.and_hms_opt(0, 0, 0).unwrap()
|
||||||
|
.and_utc()
|
||||||
|
.to_rfc3339();
|
||||||
|
let today_row: DashboardTodayRow = sqlx::query_as(
|
||||||
|
"SELECT
|
||||||
|
(SELECT COUNT(*) FROM relay_tasks WHERE created_at >= $1 AND created_at < $2) as tasks_today,
|
||||||
|
COALESCE((SELECT SUM(input_tokens) FROM usage_records WHERE created_at >= $1 AND created_at < $2), 0) as tokens_input,
|
||||||
|
COALESCE((SELECT SUM(output_tokens) FROM usage_records WHERE created_at >= $1 AND created_at < $2), 0) as tokens_output"
|
||||||
|
).bind(&today_start).bind(&tomorrow_start).fetch_one(&state.db).await?;
|
||||||
|
|
||||||
|
Ok(Json(serde_json::json!({
|
||||||
|
"total_accounts": stats_row.total_accounts,
|
||||||
|
"active_accounts": stats_row.active_accounts,
|
||||||
|
"tasks_today": today_row.tasks_today,
|
||||||
|
"active_providers": stats_row.active_providers,
|
||||||
|
"active_models": stats_row.active_models,
|
||||||
|
"tokens_today_input": today_row.tokens_input,
|
||||||
|
"tokens_today_output": today_row.tokens_output,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Devices ============
|
||||||
|
|
||||||
|
/// POST /api/v1/devices/register — 注册或更新设备
|
||||||
|
pub async fn register_device(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<serde_json::Value>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
let device_id = req.get("device_id")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.ok_or_else(|| SaasError::InvalidInput("缺少 device_id".into()))?;
|
||||||
|
let device_name = req.get("device_name").and_then(|v| v.as_str()).unwrap_or("Unknown");
|
||||||
|
let platform = req.get("platform").and_then(|v| v.as_str()).unwrap_or("unknown");
|
||||||
|
let app_version = req.get("app_version").and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let device_uuid = uuid::Uuid::new_v4().to_string();
|
||||||
|
|
||||||
|
// UPSERT: 已存在则更新 last_seen_at,不存在则插入
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO devices (id, account_id, device_id, device_name, platform, app_version, last_seen_at, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $7)
|
||||||
|
ON CONFLICT(account_id, device_id) DO UPDATE SET
|
||||||
|
device_name = $4, platform = $5, app_version = $6, last_seen_at = $7"
|
||||||
|
)
|
||||||
|
.bind(&device_uuid)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.bind(device_id)
|
||||||
|
.bind(device_name)
|
||||||
|
.bind(platform)
|
||||||
|
.bind(app_version)
|
||||||
|
.bind(&now)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
log_operation(&state.db, &ctx.account_id, "device.register", "device", device_id,
|
||||||
|
Some(serde_json::json!({"device_name": device_name, "platform": platform})),
|
||||||
|
ctx.client_ip.as_deref()).await?;
|
||||||
|
|
||||||
|
Ok(Json(serde_json::json!({"ok": true, "device_id": device_id})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/devices/heartbeat — 设备心跳
|
||||||
|
pub async fn device_heartbeat(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<serde_json::Value>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
let device_id = req.get("device_id")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.ok_or_else(|| SaasError::InvalidInput("缺少 device_id".into()))?;
|
||||||
|
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
// Also update platform/app_version if provided (supports client upgrades)
|
||||||
|
let platform = req.get("platform").and_then(|v| v.as_str());
|
||||||
|
let app_version = req.get("app_version").and_then(|v| v.as_str());
|
||||||
|
|
||||||
|
let result = if platform.is_some() || app_version.is_some() {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE devices SET last_seen_at = $1, platform = COALESCE($4, platform), app_version = COALESCE($5, app_version) WHERE account_id = $2 AND device_id = $3"
|
||||||
|
)
|
||||||
|
.bind(&now)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.bind(device_id)
|
||||||
|
.bind(platform)
|
||||||
|
.bind(app_version)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE devices SET last_seen_at = $1 WHERE account_id = $2 AND device_id = $3"
|
||||||
|
)
|
||||||
|
.bind(&now)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.bind(device_id)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?
|
||||||
|
};
|
||||||
|
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
return Err(SaasError::NotFound("设备未注册".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Json(serde_json::json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/devices?page=1&page_size=20 — 列出当前用户的设备
|
||||||
|
pub async fn list_devices(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Query(params): Query<std::collections::HashMap<String, String>>,
|
||||||
|
) -> SaasResult<Json<PaginatedResponse<serde_json::Value>>> {
|
||||||
|
let page = params.get("page").and_then(|v| v.parse().ok());
|
||||||
|
let page_size = params.get("page_size").and_then(|v| v.parse().ok());
|
||||||
|
service::list_devices(&state.db, &ctx.account_id, page, page_size).await.map(Json)
|
||||||
|
}
|
||||||
23
crates/zclaw-saas/src/account/mod.rs
Normal file
23
crates/zclaw-saas/src/account/mod.rs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
//! 账号管理模块
|
||||||
|
|
||||||
|
pub mod types;
|
||||||
|
pub mod service;
|
||||||
|
pub mod handlers;
|
||||||
|
|
||||||
|
use axum::routing::{delete, get, patch, post};
|
||||||
|
|
||||||
|
pub fn routes() -> axum::Router<crate::state::AppState> {
|
||||||
|
axum::Router::new()
|
||||||
|
.route("/api/v1/accounts", get(handlers::list_accounts))
|
||||||
|
.route("/api/v1/accounts/:id", get(handlers::get_account))
|
||||||
|
.route("/api/v1/accounts/:id", patch(handlers::update_account))
|
||||||
|
.route("/api/v1/accounts/:id/status", patch(handlers::update_status))
|
||||||
|
.route("/api/v1/tokens", get(handlers::list_tokens))
|
||||||
|
.route("/api/v1/tokens", post(handlers::create_token))
|
||||||
|
.route("/api/v1/tokens/:id", delete(handlers::revoke_token))
|
||||||
|
.route("/api/v1/logs/operations", get(handlers::list_operation_logs))
|
||||||
|
.route("/api/v1/stats/dashboard", get(handlers::dashboard_stats))
|
||||||
|
.route("/api/v1/devices", get(handlers::list_devices))
|
||||||
|
.route("/api/v1/devices/register", post(handlers::register_device))
|
||||||
|
.route("/api/v1/devices/heartbeat", post(handlers::device_heartbeat))
|
||||||
|
}
|
||||||
283
crates/zclaw-saas/src/account/service.rs
Normal file
283
crates/zclaw-saas/src/account/service.rs
Normal file
@@ -0,0 +1,283 @@
|
|||||||
|
//! 账号管理业务逻辑
|
||||||
|
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use crate::error::{SaasError, SaasResult};
|
||||||
|
use crate::common::{PaginatedResponse, normalize_pagination};
|
||||||
|
use crate::models::{AccountRow, ApiTokenRow, DeviceRow};
|
||||||
|
use super::types::*;
|
||||||
|
|
||||||
|
pub async fn list_accounts(
|
||||||
|
db: &PgPool,
|
||||||
|
query: &ListAccountsQuery,
|
||||||
|
) -> SaasResult<PaginatedResponse<serde_json::Value>> {
|
||||||
|
let page = query.page.unwrap_or(1).max(1);
|
||||||
|
let page_size = query.page_size.unwrap_or(20).min(100);
|
||||||
|
let offset = (page - 1) * page_size;
|
||||||
|
|
||||||
|
let mut where_clauses = Vec::new();
|
||||||
|
let mut params: Vec<String> = Vec::new();
|
||||||
|
let mut param_idx = 1usize;
|
||||||
|
|
||||||
|
if let Some(role) = &query.role {
|
||||||
|
where_clauses.push(format!("role = ${}", param_idx));
|
||||||
|
param_idx += 1;
|
||||||
|
params.push(role.clone());
|
||||||
|
}
|
||||||
|
if let Some(status) = &query.status {
|
||||||
|
where_clauses.push(format!("status = ${}", param_idx));
|
||||||
|
param_idx += 1;
|
||||||
|
params.push(status.clone());
|
||||||
|
}
|
||||||
|
if let Some(search) = &query.search {
|
||||||
|
where_clauses.push(format!("(username LIKE ${} OR email LIKE ${} OR display_name LIKE ${})", param_idx, param_idx + 1, param_idx + 2));
|
||||||
|
param_idx += 3;
|
||||||
|
let pattern = format!("%{}%", search);
|
||||||
|
params.push(pattern.clone());
|
||||||
|
params.push(pattern.clone());
|
||||||
|
params.push(pattern);
|
||||||
|
}
|
||||||
|
|
||||||
|
let where_sql = if where_clauses.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
format!("WHERE {}", where_clauses.join(" AND "))
|
||||||
|
};
|
||||||
|
|
||||||
|
let count_sql = format!("SELECT COUNT(*) as count FROM accounts {}", where_sql);
|
||||||
|
let mut count_query = sqlx::query_scalar::<_, i64>(&count_sql);
|
||||||
|
for p in ¶ms {
|
||||||
|
count_query = count_query.bind(p);
|
||||||
|
}
|
||||||
|
let total: i64 = count_query.fetch_one(db).await?;
|
||||||
|
|
||||||
|
let limit_idx = param_idx;
|
||||||
|
let offset_idx = param_idx + 1;
|
||||||
|
let data_sql = format!(
|
||||||
|
"SELECT id, username, email, display_name, role, status, totp_enabled, last_login_at, created_at
|
||||||
|
FROM accounts {} ORDER BY created_at DESC LIMIT ${} OFFSET ${}",
|
||||||
|
where_sql, limit_idx, offset_idx
|
||||||
|
);
|
||||||
|
let mut data_query = sqlx::query_as::<_, AccountRow>(&data_sql);
|
||||||
|
for p in ¶ms {
|
||||||
|
data_query = data_query.bind(p);
|
||||||
|
}
|
||||||
|
let rows = data_query.bind(page_size as i64).bind(offset as i64).fetch_all(db).await?;
|
||||||
|
|
||||||
|
let items: Vec<serde_json::Value> = rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| {
|
||||||
|
serde_json::json!({
|
||||||
|
"id": r.id, "username": r.username, "email": r.email, "display_name": r.display_name,
|
||||||
|
"role": r.role, "status": r.status, "totp_enabled": r.totp_enabled,
|
||||||
|
"last_login_at": r.last_login_at, "created_at": r.created_at,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(PaginatedResponse { items, total, page, page_size })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_account(db: &PgPool, account_id: &str) -> SaasResult<serde_json::Value> {
|
||||||
|
let row: Option<AccountRow> =
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, username, email, display_name, role, status, totp_enabled, last_login_at, created_at
|
||||||
|
FROM accounts WHERE id = $1"
|
||||||
|
)
|
||||||
|
.bind(account_id)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let r = row.ok_or_else(|| SaasError::NotFound(format!("账号 {} 不存在", account_id)))?;
|
||||||
|
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"id": r.id, "username": r.username, "email": r.email, "display_name": r.display_name,
|
||||||
|
"role": r.role, "status": r.status, "totp_enabled": r.totp_enabled,
|
||||||
|
"last_login_at": r.last_login_at, "created_at": r.created_at,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_account(
|
||||||
|
db: &PgPool,
|
||||||
|
account_id: &str,
|
||||||
|
req: &UpdateAccountRequest,
|
||||||
|
) -> SaasResult<serde_json::Value> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let mut updates = Vec::new();
|
||||||
|
let mut params: Vec<String> = Vec::new();
|
||||||
|
let mut param_idx = 1usize;
|
||||||
|
|
||||||
|
if let Some(ref v) = req.display_name { updates.push(format!("display_name = ${}", param_idx)); param_idx += 1; params.push(v.clone()); }
|
||||||
|
if let Some(ref v) = req.email { updates.push(format!("email = ${}", param_idx)); param_idx += 1; params.push(v.clone()); }
|
||||||
|
if let Some(ref v) = req.role { updates.push(format!("role = ${}", param_idx)); param_idx += 1; params.push(v.clone()); }
|
||||||
|
if let Some(ref v) = req.avatar_url { updates.push(format!("avatar_url = ${}", param_idx)); param_idx += 1; params.push(v.clone()); }
|
||||||
|
|
||||||
|
if updates.is_empty() {
|
||||||
|
return get_account(db, account_id).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
updates.push(format!("updated_at = ${}", param_idx));
|
||||||
|
param_idx += 1;
|
||||||
|
params.push(now.clone());
|
||||||
|
params.push(account_id.to_string());
|
||||||
|
|
||||||
|
let sql = format!("UPDATE accounts SET {} WHERE id = ${}", updates.join(", "), param_idx);
|
||||||
|
let mut query = sqlx::query(&sql);
|
||||||
|
for p in ¶ms {
|
||||||
|
query = query.bind(p);
|
||||||
|
}
|
||||||
|
query.execute(db).await?;
|
||||||
|
get_account(db, account_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_account_status(
|
||||||
|
db: &PgPool,
|
||||||
|
account_id: &str,
|
||||||
|
status: &str,
|
||||||
|
) -> SaasResult<()> {
|
||||||
|
let valid = ["active", "disabled", "suspended"];
|
||||||
|
if !valid.contains(&status) {
|
||||||
|
return Err(SaasError::InvalidInput(format!("无效状态: {},有效值: {:?}", status, valid)));
|
||||||
|
}
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let result = sqlx::query("UPDATE accounts SET status = $1, updated_at = $2 WHERE id = $3")
|
||||||
|
.bind(status).bind(&now).bind(account_id)
|
||||||
|
.execute(db).await?;
|
||||||
|
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
return Err(SaasError::NotFound(format!("账号 {} 不存在", account_id)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_api_token(
|
||||||
|
db: &PgPool,
|
||||||
|
account_id: &str,
|
||||||
|
req: &CreateTokenRequest,
|
||||||
|
) -> SaasResult<TokenInfo> {
|
||||||
|
use sha2::{Sha256, Digest};
|
||||||
|
|
||||||
|
let mut bytes = [0u8; 48];
|
||||||
|
use rand::RngCore;
|
||||||
|
rand::thread_rng().fill_bytes(&mut bytes);
|
||||||
|
let raw_token = format!("zclaw_{}", hex::encode(bytes));
|
||||||
|
let token_hash = hex::encode(Sha256::digest(raw_token.as_bytes()));
|
||||||
|
let token_prefix = raw_token[..8].to_string();
|
||||||
|
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let expires_at = req.expires_days.map(|d| {
|
||||||
|
(chrono::Utc::now() + chrono::Duration::days(d)).to_rfc3339()
|
||||||
|
});
|
||||||
|
let permissions = serde_json::to_string(&req.permissions)?;
|
||||||
|
let token_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO api_tokens (id, account_id, name, token_hash, token_prefix, permissions, created_at, expires_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"
|
||||||
|
)
|
||||||
|
.bind(&token_id)
|
||||||
|
.bind(account_id)
|
||||||
|
.bind(&req.name)
|
||||||
|
.bind(&token_hash)
|
||||||
|
.bind(&token_prefix)
|
||||||
|
.bind(&permissions)
|
||||||
|
.bind(&now)
|
||||||
|
.bind(&expires_at)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(TokenInfo {
|
||||||
|
id: token_id,
|
||||||
|
name: req.name.clone(),
|
||||||
|
token_prefix,
|
||||||
|
permissions: req.permissions.clone(),
|
||||||
|
last_used_at: None,
|
||||||
|
expires_at,
|
||||||
|
created_at: now,
|
||||||
|
token: Some(raw_token),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_api_tokens(
|
||||||
|
db: &PgPool,
|
||||||
|
account_id: &str,
|
||||||
|
page: Option<u32>,
|
||||||
|
page_size: Option<u32>,
|
||||||
|
) -> SaasResult<PaginatedResponse<TokenInfo>> {
|
||||||
|
let (p, ps, offset) = normalize_pagination(page, page_size);
|
||||||
|
|
||||||
|
let total: (i64,) = sqlx::query_as(
|
||||||
|
"SELECT COUNT(*) FROM api_tokens WHERE account_id = $1 AND revoked_at IS NULL"
|
||||||
|
)
|
||||||
|
.bind(account_id)
|
||||||
|
.fetch_one(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let rows: Vec<ApiTokenRow> =
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, name, token_prefix, permissions, last_used_at, expires_at, created_at
|
||||||
|
FROM api_tokens WHERE account_id = $1 AND revoked_at IS NULL ORDER BY created_at DESC LIMIT $2 OFFSET $3"
|
||||||
|
)
|
||||||
|
.bind(account_id)
|
||||||
|
.bind(ps as i64)
|
||||||
|
.bind(offset)
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let items = rows.into_iter().map(|r| {
|
||||||
|
let permissions: Vec<String> = serde_json::from_str(&r.permissions).unwrap_or_default();
|
||||||
|
TokenInfo { id: r.id, name: r.name, token_prefix: r.token_prefix, permissions, last_used_at: r.last_used_at, expires_at: r.expires_at, created_at: r.created_at, token: None, }
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
Ok(PaginatedResponse { items, total: total.0, page: p, page_size: ps })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_devices(
|
||||||
|
db: &PgPool,
|
||||||
|
account_id: &str,
|
||||||
|
page: Option<u32>,
|
||||||
|
page_size: Option<u32>,
|
||||||
|
) -> SaasResult<PaginatedResponse<serde_json::Value>> {
|
||||||
|
let (p, ps, offset) = normalize_pagination(page, page_size);
|
||||||
|
|
||||||
|
let total: (i64,) = sqlx::query_as(
|
||||||
|
"SELECT COUNT(*) FROM devices WHERE account_id = $1"
|
||||||
|
)
|
||||||
|
.bind(account_id)
|
||||||
|
.fetch_one(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let rows: Vec<DeviceRow> =
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, device_id, device_name, platform, app_version, last_seen_at, created_at
|
||||||
|
FROM devices WHERE account_id = $1 ORDER BY last_seen_at DESC LIMIT $2 OFFSET $3"
|
||||||
|
)
|
||||||
|
.bind(account_id)
|
||||||
|
.bind(ps as i64)
|
||||||
|
.bind(offset)
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let items: Vec<serde_json::Value> = rows.into_iter().map(|r| {
|
||||||
|
serde_json::json!({
|
||||||
|
"id": r.id, "device_id": r.device_id,
|
||||||
|
"device_name": r.device_name, "platform": r.platform, "app_version": r.app_version,
|
||||||
|
"last_seen_at": r.last_seen_at, "created_at": r.created_at,
|
||||||
|
})
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
Ok(PaginatedResponse { items, total: total.0, page: p, page_size: ps })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn revoke_api_token(db: &PgPool, token_id: &str, account_id: &str) -> SaasResult<()> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let result = sqlx::query(
|
||||||
|
"UPDATE api_tokens SET revoked_at = $1 WHERE id = $2 AND account_id = $3 AND revoked_at IS NULL"
|
||||||
|
)
|
||||||
|
.bind(&now).bind(token_id).bind(account_id)
|
||||||
|
.execute(db).await?;
|
||||||
|
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
return Err(SaasError::NotFound("Token 不存在或已撤销".into()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
48
crates/zclaw-saas/src/account/types.rs
Normal file
48
crates/zclaw-saas/src/account/types.rs
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
//! 账号管理类型
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
// Re-export from common module
|
||||||
|
pub use crate::common::PaginatedResponse;
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct UpdateAccountRequest {
|
||||||
|
pub display_name: Option<String>,
|
||||||
|
pub email: Option<String>,
|
||||||
|
pub role: Option<String>,
|
||||||
|
pub avatar_url: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct UpdateStatusRequest {
|
||||||
|
pub status: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct ListAccountsQuery {
|
||||||
|
pub page: Option<u32>,
|
||||||
|
pub page_size: Option<u32>,
|
||||||
|
pub role: Option<String>,
|
||||||
|
pub status: Option<String>,
|
||||||
|
pub search: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct CreateTokenRequest {
|
||||||
|
pub name: String,
|
||||||
|
pub permissions: Vec<String>,
|
||||||
|
pub expires_days: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct TokenInfo {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub token_prefix: String,
|
||||||
|
pub permissions: Vec<String>,
|
||||||
|
pub last_used_at: Option<String>,
|
||||||
|
pub expires_at: Option<String>,
|
||||||
|
pub created_at: String,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub token: Option<String>,
|
||||||
|
}
|
||||||
104
crates/zclaw-saas/src/agent_template/handlers.rs
Normal file
104
crates/zclaw-saas/src/agent_template/handlers.rs
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
//! Agent 配置模板 HTTP 处理器
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
extract::{Extension, Path, Query, State},
|
||||||
|
Json,
|
||||||
|
};
|
||||||
|
use crate::state::AppState;
|
||||||
|
use crate::error::SaasResult;
|
||||||
|
use crate::auth::types::AuthContext;
|
||||||
|
use crate::auth::handlers::{log_operation, check_permission};
|
||||||
|
use super::types::*;
|
||||||
|
use super::service;
|
||||||
|
|
||||||
|
/// GET /api/v1/agent-templates — 列出 Agent 模板
|
||||||
|
pub async fn list_templates(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Query(query): Query<AgentTemplateListQuery>,
|
||||||
|
) -> SaasResult<Json<crate::common::PaginatedResponse<AgentTemplateInfo>>> {
|
||||||
|
check_permission(&ctx, "model:read")?;
|
||||||
|
Ok(Json(service::list_templates(&state.db, &query).await?))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/agent-templates — 创建 Agent 模板
|
||||||
|
pub async fn create_template(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<CreateAgentTemplateRequest>,
|
||||||
|
) -> SaasResult<Json<AgentTemplateInfo>> {
|
||||||
|
check_permission(&ctx, "model:manage")?;
|
||||||
|
|
||||||
|
let category = req.category.as_deref().unwrap_or("general");
|
||||||
|
let source = req.source.as_deref().unwrap_or("custom");
|
||||||
|
let visibility = req.visibility.as_deref().unwrap_or("public");
|
||||||
|
let tools = req.tools.as_deref().unwrap_or(&[]);
|
||||||
|
let capabilities = req.capabilities.as_deref().unwrap_or(&[]);
|
||||||
|
|
||||||
|
let result = service::create_template(
|
||||||
|
&state.db, &req.name, req.description.as_deref(),
|
||||||
|
category, source, req.model.as_deref(),
|
||||||
|
req.system_prompt.as_deref(),
|
||||||
|
tools, capabilities,
|
||||||
|
req.temperature, req.max_tokens, visibility,
|
||||||
|
).await?;
|
||||||
|
|
||||||
|
log_operation(&state.db, &ctx.account_id, "agent_template.create", "agent_template", &result.id,
|
||||||
|
Some(serde_json::json!({"name": req.name})), ctx.client_ip.as_deref()).await?;
|
||||||
|
|
||||||
|
Ok(Json(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/agent-templates/:id — 获取单个 Agent 模板
|
||||||
|
pub async fn get_template(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> SaasResult<Json<AgentTemplateInfo>> {
|
||||||
|
check_permission(&ctx, "model:read")?;
|
||||||
|
Ok(Json(service::get_template(&state.db, &id).await?))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/agent-templates/:id — 更新 Agent 模板
|
||||||
|
pub async fn update_template(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Json(req): Json<UpdateAgentTemplateRequest>,
|
||||||
|
) -> SaasResult<Json<AgentTemplateInfo>> {
|
||||||
|
check_permission(&ctx, "model:manage")?;
|
||||||
|
|
||||||
|
let result = service::update_template(
|
||||||
|
&state.db, &id,
|
||||||
|
req.description.as_deref(),
|
||||||
|
req.model.as_deref(),
|
||||||
|
req.system_prompt.as_deref(),
|
||||||
|
req.tools.as_deref(),
|
||||||
|
req.capabilities.as_deref(),
|
||||||
|
req.temperature,
|
||||||
|
req.max_tokens,
|
||||||
|
req.visibility.as_deref(),
|
||||||
|
req.status.as_deref(),
|
||||||
|
).await?;
|
||||||
|
|
||||||
|
log_operation(&state.db, &ctx.account_id, "agent_template.update", "agent_template", &id,
|
||||||
|
None, ctx.client_ip.as_deref()).await?;
|
||||||
|
|
||||||
|
Ok(Json(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// DELETE /api/v1/agent-templates/:id — 归档 Agent 模板
|
||||||
|
pub async fn archive_template(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> SaasResult<Json<AgentTemplateInfo>> {
|
||||||
|
check_permission(&ctx, "model:manage")?;
|
||||||
|
|
||||||
|
let result = service::archive_template(&state.db, &id).await?;
|
||||||
|
|
||||||
|
log_operation(&state.db, &ctx.account_id, "agent_template.archive", "agent_template", &id,
|
||||||
|
None, ctx.client_ip.as_deref()).await?;
|
||||||
|
|
||||||
|
Ok(Json(result))
|
||||||
|
}
|
||||||
17
crates/zclaw-saas/src/agent_template/mod.rs
Normal file
17
crates/zclaw-saas/src/agent_template/mod.rs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
//! Agent 配置模板管理模块
|
||||||
|
|
||||||
|
pub mod types;
|
||||||
|
pub mod service;
|
||||||
|
pub mod handlers;
|
||||||
|
|
||||||
|
use axum::routing::{delete, get, post};
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
/// Agent 模板管理路由 (需要认证)
|
||||||
|
pub fn routes() -> axum::Router<AppState> {
|
||||||
|
axum::Router::new()
|
||||||
|
.route("/api/v1/agent-templates", get(handlers::list_templates).post(handlers::create_template))
|
||||||
|
.route("/api/v1/agent-templates/:id", get(handlers::get_template))
|
||||||
|
.route("/api/v1/agent-templates/:id", post(handlers::update_template))
|
||||||
|
.route("/api/v1/agent-templates/:id", delete(handlers::archive_template))
|
||||||
|
}
|
||||||
272
crates/zclaw-saas/src/agent_template/service.rs
Normal file
272
crates/zclaw-saas/src/agent_template/service.rs
Normal file
@@ -0,0 +1,272 @@
|
|||||||
|
//! Agent 配置模板业务逻辑
|
||||||
|
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use crate::error::{SaasError, SaasResult};
|
||||||
|
use super::types::*;
|
||||||
|
|
||||||
|
fn row_to_template(
|
||||||
|
row: (String, String, Option<String>, String, String, Option<String>, Option<String>,
|
||||||
|
String, String, Option<f64>, Option<i32>, String, String, i32, String, String),
|
||||||
|
) -> AgentTemplateInfo {
|
||||||
|
AgentTemplateInfo {
|
||||||
|
id: row.0, name: row.1, description: row.2, category: row.3, source: row.4,
|
||||||
|
model: row.5, system_prompt: row.6, tools: serde_json::from_str(&row.7).unwrap_or_default(),
|
||||||
|
capabilities: serde_json::from_str(&row.8).unwrap_or_default(),
|
||||||
|
temperature: row.9, max_tokens: row.10, visibility: row.11, status: row.12,
|
||||||
|
current_version: row.13, created_at: row.14, updated_at: row.15,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建 Agent 模板
|
||||||
|
pub async fn create_template(
|
||||||
|
db: &PgPool,
|
||||||
|
name: &str,
|
||||||
|
description: Option<&str>,
|
||||||
|
category: &str,
|
||||||
|
source: &str,
|
||||||
|
model: Option<&str>,
|
||||||
|
system_prompt: Option<&str>,
|
||||||
|
tools: &[String],
|
||||||
|
capabilities: &[String],
|
||||||
|
temperature: Option<f64>,
|
||||||
|
max_tokens: Option<i32>,
|
||||||
|
visibility: &str,
|
||||||
|
) -> SaasResult<AgentTemplateInfo> {
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let tools_json = serde_json::to_string(tools).unwrap_or_else(|_| "[]".to_string());
|
||||||
|
let caps_json = serde_json::to_string(capabilities).unwrap_or_else(|_| "[]".to_string());
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO agent_templates (id, name, description, category, source, model, system_prompt,
|
||||||
|
tools, capabilities, temperature, max_tokens, visibility, status, current_version, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, 'active', 1, $13, $13)"
|
||||||
|
)
|
||||||
|
.bind(&id).bind(name).bind(description).bind(category).bind(source)
|
||||||
|
.bind(model).bind(system_prompt).bind(&tools_json).bind(&caps_json)
|
||||||
|
.bind(temperature).bind(max_tokens).bind(visibility).bind(&now)
|
||||||
|
.execute(db).await.map_err(|e| {
|
||||||
|
if e.to_string().contains("unique") {
|
||||||
|
SaasError::AlreadyExists(format!("Agent 模板 '{}' 已存在", name))
|
||||||
|
} else {
|
||||||
|
SaasError::Database(e)
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
|
||||||
|
get_template(db, &id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 获取单个模板
|
||||||
|
pub async fn get_template(db: &PgPool, id: &str) -> SaasResult<AgentTemplateInfo> {
|
||||||
|
let row: Option<_> = sqlx::query_as(
|
||||||
|
"SELECT id, name, description, category, source, model, system_prompt,
|
||||||
|
tools, capabilities, temperature, max_tokens, visibility, status,
|
||||||
|
current_version, created_at, updated_at
|
||||||
|
FROM agent_templates WHERE id = $1"
|
||||||
|
).bind(id).fetch_optional(db).await?;
|
||||||
|
|
||||||
|
row.map(row_to_template)
|
||||||
|
.ok_or_else(|| SaasError::NotFound(format!("Agent 模板 {} 不存在", id)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 列出模板(分页 + 过滤)
|
||||||
|
/// 使用动态参数化查询,安全拼接 WHERE 条件。
|
||||||
|
pub async fn list_templates(
|
||||||
|
db: &PgPool,
|
||||||
|
query: &AgentTemplateListQuery,
|
||||||
|
) -> SaasResult<crate::common::PaginatedResponse<AgentTemplateInfo>> {
|
||||||
|
let page = query.page.unwrap_or(1).max(1);
|
||||||
|
let page_size = query.page_size.unwrap_or(20).min(100);
|
||||||
|
let offset = ((page - 1) * page_size) as i64;
|
||||||
|
|
||||||
|
// 动态构建参数化 WHERE 子句
|
||||||
|
let mut conditions: Vec<String> = vec!["1=1".to_string()];
|
||||||
|
let mut param_idx = 1u32;
|
||||||
|
let mut cat_bind: Option<String> = None;
|
||||||
|
let mut src_bind: Option<String> = None;
|
||||||
|
let mut vis_bind: Option<String> = None;
|
||||||
|
let mut st_bind: Option<String> = None;
|
||||||
|
|
||||||
|
if let Some(ref cat) = query.category {
|
||||||
|
param_idx += 1;
|
||||||
|
conditions.push(format!("category = ${}", param_idx));
|
||||||
|
cat_bind = Some(cat.clone());
|
||||||
|
}
|
||||||
|
if let Some(ref src) = query.source {
|
||||||
|
param_idx += 1;
|
||||||
|
conditions.push(format!("source = ${}", param_idx));
|
||||||
|
src_bind = Some(src.clone());
|
||||||
|
}
|
||||||
|
if let Some(ref vis) = query.visibility {
|
||||||
|
param_idx += 1;
|
||||||
|
conditions.push(format!("visibility = ${}", param_idx));
|
||||||
|
vis_bind = Some(vis.clone());
|
||||||
|
}
|
||||||
|
if let Some(ref st) = query.status {
|
||||||
|
param_idx += 1;
|
||||||
|
conditions.push(format!("status = ${}", param_idx));
|
||||||
|
st_bind = Some(st.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
let where_clause = conditions.join(" AND ");
|
||||||
|
|
||||||
|
// COUNT 查询: WHERE 参数绑定 ($1..$N)
|
||||||
|
let count_idx = param_idx;
|
||||||
|
let count_sql = format!(
|
||||||
|
"SELECT COUNT(*) FROM agent_templates WHERE {}",
|
||||||
|
where_clause
|
||||||
|
);
|
||||||
|
let count_limit_idx = count_idx + 1;
|
||||||
|
let count_offset_idx = count_limit_idx + 1;
|
||||||
|
let data_sql = format!(
|
||||||
|
"SELECT id, name, description, category, source, model, system_prompt,
|
||||||
|
tools, capabilities, temperature, max_tokens, visibility, status,
|
||||||
|
current_version, created_at, updated_at
|
||||||
|
FROM agent_templates WHERE {} ORDER BY created_at DESC LIMIT ${} OFFSET ${}",
|
||||||
|
where_clause, count_limit_idx, count_offset_idx
|
||||||
|
);
|
||||||
|
|
||||||
|
// 构建 COUNT 查询并绑定参数
|
||||||
|
let mut count_q = sqlx::query_scalar::<_, i64>(&count_sql);
|
||||||
|
if let Some(ref v) = cat_bind { count_q = count_q.bind(v); }
|
||||||
|
if let Some(ref v) = src_bind { count_q = count_q.bind(v); }
|
||||||
|
if let Some(ref v) = vis_bind { count_q = count_q.bind(v); }
|
||||||
|
if let Some(ref v) = st_bind { count_q = count_q.bind(v); }
|
||||||
|
let total: i64 = count_q.fetch_one(db).await?;
|
||||||
|
|
||||||
|
// 构建数据查询并绑定参数
|
||||||
|
let mut data_q = sqlx::query_as::<_, (
|
||||||
|
String, String, Option<String>, String, String, Option<String>, Option<String>,
|
||||||
|
String, String, Option<f64>, Option<i32>, String, String, i32, String, String
|
||||||
|
)>(&data_sql);
|
||||||
|
if let Some(ref v) = cat_bind { data_q = data_q.bind(v); }
|
||||||
|
if let Some(ref v) = src_bind { data_q = data_q.bind(v); }
|
||||||
|
if let Some(ref v) = vis_bind { data_q = data_q.bind(v); }
|
||||||
|
if let Some(ref v) = st_bind { data_q = data_q.bind(v); }
|
||||||
|
data_q = data_q.bind(page_size as i64).bind(offset);
|
||||||
|
|
||||||
|
let rows = data_q.fetch_all(db).await?;
|
||||||
|
let items = rows.into_iter().map(row_to_template).collect();
|
||||||
|
|
||||||
|
Ok(crate::common::PaginatedResponse { items, total, page, page_size })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 更新模板
|
||||||
|
/// 使用动态参数化查询,安全拼接 SET 子句。
|
||||||
|
pub async fn update_template(
|
||||||
|
db: &PgPool,
|
||||||
|
id: &str,
|
||||||
|
description: Option<&str>,
|
||||||
|
model: Option<&str>,
|
||||||
|
system_prompt: Option<&str>,
|
||||||
|
tools: Option<&[String]>,
|
||||||
|
capabilities: Option<&[String]>,
|
||||||
|
temperature: Option<f64>,
|
||||||
|
max_tokens: Option<i32>,
|
||||||
|
visibility: Option<&str>,
|
||||||
|
status: Option<&str>,
|
||||||
|
) -> SaasResult<AgentTemplateInfo> {
|
||||||
|
// 确认存在
|
||||||
|
get_template(db, id).await?;
|
||||||
|
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let mut set_clauses: Vec<String> = vec![];
|
||||||
|
let mut param_idx = 1u32;
|
||||||
|
|
||||||
|
// 收集需要绑定的值(按顺序)
|
||||||
|
let mut desc_val: Option<String> = None;
|
||||||
|
let mut model_val: Option<String> = None;
|
||||||
|
let mut sp_val: Option<String> = None;
|
||||||
|
let mut tools_val: Option<String> = None;
|
||||||
|
let mut caps_val: Option<String> = None;
|
||||||
|
let mut temp_val: Option<f64> = None;
|
||||||
|
let mut mt_val: Option<i32> = None;
|
||||||
|
let mut vis_val: Option<String> = None;
|
||||||
|
let mut st_val: Option<String> = None;
|
||||||
|
|
||||||
|
if let Some(desc) = description {
|
||||||
|
param_idx += 1;
|
||||||
|
set_clauses.push(format!("description = ${}", param_idx));
|
||||||
|
desc_val = Some(desc.to_string());
|
||||||
|
}
|
||||||
|
if let Some(m) = model {
|
||||||
|
param_idx += 1;
|
||||||
|
set_clauses.push(format!("model = ${}", param_idx));
|
||||||
|
model_val = Some(m.to_string());
|
||||||
|
}
|
||||||
|
if let Some(sp) = system_prompt {
|
||||||
|
param_idx += 1;
|
||||||
|
set_clauses.push(format!("system_prompt = ${}", param_idx));
|
||||||
|
sp_val = Some(sp.to_string());
|
||||||
|
}
|
||||||
|
if let Some(t) = tools {
|
||||||
|
let json = serde_json::to_string(t).unwrap_or_else(|_| "[]".to_string());
|
||||||
|
param_idx += 1;
|
||||||
|
set_clauses.push(format!("tools = ${}", param_idx));
|
||||||
|
tools_val = Some(json);
|
||||||
|
}
|
||||||
|
if let Some(c) = capabilities {
|
||||||
|
let json = serde_json::to_string(c).unwrap_or_else(|_| "[]".to_string());
|
||||||
|
param_idx += 1;
|
||||||
|
set_clauses.push(format!("capabilities = ${}", param_idx));
|
||||||
|
caps_val = Some(json);
|
||||||
|
}
|
||||||
|
if let Some(t) = temperature {
|
||||||
|
param_idx += 1;
|
||||||
|
set_clauses.push(format!("temperature = ${}", param_idx));
|
||||||
|
temp_val = Some(t);
|
||||||
|
}
|
||||||
|
if let Some(m) = max_tokens {
|
||||||
|
param_idx += 1;
|
||||||
|
set_clauses.push(format!("max_tokens = ${}", param_idx));
|
||||||
|
mt_val = Some(m);
|
||||||
|
}
|
||||||
|
if let Some(v) = visibility {
|
||||||
|
param_idx += 1;
|
||||||
|
set_clauses.push(format!("visibility = ${}", param_idx));
|
||||||
|
vis_val = Some(v.to_string());
|
||||||
|
}
|
||||||
|
if let Some(s) = status {
|
||||||
|
param_idx += 1;
|
||||||
|
set_clauses.push(format!("status = ${}", param_idx));
|
||||||
|
st_val = Some(s.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
if set_clauses.is_empty() {
|
||||||
|
return get_template(db, id).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// updated_at
|
||||||
|
param_idx += 1;
|
||||||
|
set_clauses.push(format!("updated_at = ${}", param_idx));
|
||||||
|
|
||||||
|
// WHERE id = $N
|
||||||
|
let id_idx = param_idx + 1;
|
||||||
|
|
||||||
|
let sql = format!(
|
||||||
|
"UPDATE agent_templates SET {} WHERE id = ${}",
|
||||||
|
set_clauses.join(", "), id_idx
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut q = sqlx::query(&sql);
|
||||||
|
if let Some(ref v) = desc_val { q = q.bind(v); }
|
||||||
|
if let Some(ref v) = model_val { q = q.bind(v); }
|
||||||
|
if let Some(ref v) = sp_val { q = q.bind(v); }
|
||||||
|
if let Some(ref v) = tools_val { q = q.bind(v); }
|
||||||
|
if let Some(ref v) = caps_val { q = q.bind(v); }
|
||||||
|
if let Some(v) = temp_val { q = q.bind(v); }
|
||||||
|
if let Some(v) = mt_val { q = q.bind(v); }
|
||||||
|
if let Some(ref v) = vis_val { q = q.bind(v); }
|
||||||
|
if let Some(ref v) = st_val { q = q.bind(v); }
|
||||||
|
q = q.bind(&now);
|
||||||
|
q = q.bind(id);
|
||||||
|
|
||||||
|
q.execute(db).await?;
|
||||||
|
|
||||||
|
get_template(db, id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 归档模板
|
||||||
|
pub async fn archive_template(db: &PgPool, id: &str) -> SaasResult<AgentTemplateInfo> {
|
||||||
|
update_template(db, id, None, None, None, None, None, None, None, None, Some("archived")).await
|
||||||
|
}
|
||||||
65
crates/zclaw-saas/src/agent_template/types.rs
Normal file
65
crates/zclaw-saas/src/agent_template/types.rs
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
//! Agent 配置模板类型定义
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
// --- Agent Template ---
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct AgentTemplateInfo {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub description: Option<String>,
|
||||||
|
pub category: String,
|
||||||
|
pub source: String,
|
||||||
|
pub model: Option<String>,
|
||||||
|
pub system_prompt: Option<String>,
|
||||||
|
pub tools: Vec<String>,
|
||||||
|
pub capabilities: Vec<String>,
|
||||||
|
pub temperature: Option<f64>,
|
||||||
|
pub max_tokens: Option<i32>,
|
||||||
|
pub visibility: String,
|
||||||
|
pub status: String,
|
||||||
|
pub current_version: i32,
|
||||||
|
pub created_at: String,
|
||||||
|
pub updated_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct CreateAgentTemplateRequest {
|
||||||
|
pub name: String,
|
||||||
|
pub description: Option<String>,
|
||||||
|
pub category: Option<String>,
|
||||||
|
pub source: Option<String>,
|
||||||
|
pub model: Option<String>,
|
||||||
|
pub system_prompt: Option<String>,
|
||||||
|
pub tools: Option<Vec<String>>,
|
||||||
|
pub capabilities: Option<Vec<String>>,
|
||||||
|
pub temperature: Option<f64>,
|
||||||
|
pub max_tokens: Option<i32>,
|
||||||
|
pub visibility: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct UpdateAgentTemplateRequest {
|
||||||
|
pub description: Option<String>,
|
||||||
|
pub model: Option<String>,
|
||||||
|
pub system_prompt: Option<String>,
|
||||||
|
pub tools: Option<Vec<String>>,
|
||||||
|
pub capabilities: Option<Vec<String>>,
|
||||||
|
pub temperature: Option<f64>,
|
||||||
|
pub max_tokens: Option<i32>,
|
||||||
|
pub visibility: Option<String>,
|
||||||
|
pub status: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- List ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct AgentTemplateListQuery {
|
||||||
|
pub category: Option<String>,
|
||||||
|
pub source: Option<String>,
|
||||||
|
pub visibility: Option<String>,
|
||||||
|
pub status: Option<String>,
|
||||||
|
pub page: Option<u32>,
|
||||||
|
pub page_size: Option<u32>,
|
||||||
|
}
|
||||||
457
crates/zclaw-saas/src/auth/handlers.rs
Normal file
457
crates/zclaw-saas/src/auth/handlers.rs
Normal file
@@ -0,0 +1,457 @@
|
|||||||
|
//! 认证 HTTP 处理器
|
||||||
|
|
||||||
|
use axum::{extract::{State, ConnectInfo}, http::StatusCode, Json};
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use secrecy::ExposeSecret;
|
||||||
|
use crate::state::AppState;
|
||||||
|
use crate::error::{SaasError, SaasResult};
|
||||||
|
use crate::models::{AccountAuthRow, AccountLoginRow};
|
||||||
|
use super::{
|
||||||
|
jwt::{create_token, create_refresh_token, verify_token, verify_token_skip_expiry},
|
||||||
|
password::{hash_password, verify_password},
|
||||||
|
types::{AuthContext, LoginRequest, LoginResponse, RegisterRequest, ChangePasswordRequest, AccountPublic, RefreshRequest},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// POST /api/v1/auth/register
|
||||||
|
/// 注册成功后自动签发 JWT,返回与 login 一致的 LoginResponse
|
||||||
|
pub async fn register(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||||
|
Json(req): Json<RegisterRequest>,
|
||||||
|
) -> SaasResult<(StatusCode, Json<LoginResponse>)> {
|
||||||
|
if req.username.len() < 3 {
|
||||||
|
return Err(SaasError::InvalidInput("用户名至少 3 个字符".into()));
|
||||||
|
}
|
||||||
|
if req.username.len() > 32 {
|
||||||
|
return Err(SaasError::InvalidInput("用户名最多 32 个字符".into()));
|
||||||
|
}
|
||||||
|
let username_re = regex::Regex::new(r"^[a-zA-Z0-9_-]+$").unwrap();
|
||||||
|
if !username_re.is_match(&req.username) {
|
||||||
|
return Err(SaasError::InvalidInput("用户名只能包含字母、数字、下划线和连字符".into()));
|
||||||
|
}
|
||||||
|
if !req.email.contains('@') || !req.email.contains('.') {
|
||||||
|
return Err(SaasError::InvalidInput("邮箱格式不正确".into()));
|
||||||
|
}
|
||||||
|
if req.password.len() < 8 {
|
||||||
|
return Err(SaasError::InvalidInput("密码至少 8 个字符".into()));
|
||||||
|
}
|
||||||
|
if req.password.len() > 128 {
|
||||||
|
return Err(SaasError::InvalidInput("密码最多 128 个字符".into()));
|
||||||
|
}
|
||||||
|
if let Some(ref name) = req.display_name {
|
||||||
|
if name.len() > 64 {
|
||||||
|
return Err(SaasError::InvalidInput("显示名称最多 64 个字符".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let existing: Vec<(String,)> = sqlx::query_as(
|
||||||
|
"SELECT id FROM accounts WHERE username = $1 OR email = $2"
|
||||||
|
)
|
||||||
|
.bind(&req.username)
|
||||||
|
.bind(&req.email)
|
||||||
|
.fetch_all(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if !existing.is_empty() {
|
||||||
|
return Err(SaasError::AlreadyExists("用户名或邮箱已存在".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let password_hash = hash_password(&req.password)?;
|
||||||
|
let account_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let role = "user".to_string(); // 注册固定为普通用户,角色由管理员分配
|
||||||
|
let display_name = req.display_name.unwrap_or_default();
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO accounts (id, username, email, password_hash, display_name, role, status, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, 'active', $7, $7)"
|
||||||
|
)
|
||||||
|
.bind(&account_id)
|
||||||
|
.bind(&req.username)
|
||||||
|
.bind(&req.email)
|
||||||
|
.bind(&password_hash)
|
||||||
|
.bind(&display_name)
|
||||||
|
.bind(&role)
|
||||||
|
.bind(&now)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let client_ip = addr.ip().to_string();
|
||||||
|
log_operation(&state.db, &account_id, "account.create", "account", &account_id, None, Some(&client_ip)).await?;
|
||||||
|
|
||||||
|
// 注册成功后自动签发 JWT + Refresh Token
|
||||||
|
let permissions = get_role_permissions(&state.db, &state.role_permissions_cache, &role).await?;
|
||||||
|
let config = state.config.read().await;
|
||||||
|
let token = create_token(
|
||||||
|
&account_id, &role, permissions.clone(),
|
||||||
|
state.jwt_secret.expose_secret(),
|
||||||
|
config.auth.jwt_expiration_hours,
|
||||||
|
)?;
|
||||||
|
let refresh_token = create_refresh_token(
|
||||||
|
&account_id, &role, permissions,
|
||||||
|
state.jwt_secret.expose_secret(),
|
||||||
|
config.auth.refresh_token_hours,
|
||||||
|
)?;
|
||||||
|
drop(config);
|
||||||
|
|
||||||
|
store_refresh_token(
|
||||||
|
&state.db, &account_id, &refresh_token,
|
||||||
|
state.jwt_secret.expose_secret(), 168,
|
||||||
|
).await?;
|
||||||
|
|
||||||
|
Ok((StatusCode::CREATED, Json(LoginResponse {
|
||||||
|
token,
|
||||||
|
refresh_token,
|
||||||
|
account: AccountPublic {
|
||||||
|
id: account_id,
|
||||||
|
username: req.username,
|
||||||
|
email: req.email,
|
||||||
|
display_name,
|
||||||
|
role,
|
||||||
|
status: "active".into(),
|
||||||
|
totp_enabled: false,
|
||||||
|
created_at: now,
|
||||||
|
},
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/auth/login
|
||||||
|
pub async fn login(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||||
|
Json(req): Json<LoginRequest>,
|
||||||
|
) -> SaasResult<Json<LoginResponse>> {
|
||||||
|
// 一次查询获取用户信息 + password_hash + totp_secret(合并原来的 3 次查询)
|
||||||
|
let row: Option<AccountLoginRow> =
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, username, email, display_name, role, status, totp_enabled,
|
||||||
|
password_hash, totp_secret, created_at
|
||||||
|
FROM accounts WHERE username = $1 OR email = $1"
|
||||||
|
)
|
||||||
|
.bind(&req.username)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let r = row.ok_or_else(|| SaasError::AuthError("用户名或密码错误".into()))?;
|
||||||
|
|
||||||
|
if r.status != "active" {
|
||||||
|
return Err(SaasError::Forbidden(format!("账号已{},请联系管理员", r.status)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !verify_password(&req.password, &r.password_hash)? {
|
||||||
|
return Err(SaasError::AuthError("用户名或密码错误".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// TOTP 验证: 如果用户已启用 2FA,必须提供有效 TOTP 码
|
||||||
|
if r.totp_enabled {
|
||||||
|
let code = req.totp_code.as_deref()
|
||||||
|
.ok_or_else(|| SaasError::Totp("此账号已启用双因素认证,请提供 TOTP 码".into()))?;
|
||||||
|
|
||||||
|
let secret = r.totp_secret.clone().ok_or_else(|| {
|
||||||
|
SaasError::Internal("TOTP 已启用但密钥丢失,请联系管理员".into())
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// 解密 TOTP secret (兼容旧的明文格式)
|
||||||
|
let config = state.config.read().await;
|
||||||
|
let enc_key = config.totp_encryption_key()
|
||||||
|
.map_err(|e| SaasError::Internal(e.to_string()))?;
|
||||||
|
let secret = super::totp::decrypt_totp_for_login(&secret, &enc_key)?;
|
||||||
|
|
||||||
|
if !super::totp::verify_totp_code(&secret, code) {
|
||||||
|
return Err(SaasError::Totp("TOTP 码错误或已过期".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let permissions = get_role_permissions(&state.db, &state.role_permissions_cache, &r.role).await?;
|
||||||
|
let config = state.config.read().await;
|
||||||
|
let token = create_token(
|
||||||
|
&r.id, &r.role, permissions.clone(),
|
||||||
|
state.jwt_secret.expose_secret(),
|
||||||
|
config.auth.jwt_expiration_hours,
|
||||||
|
)?;
|
||||||
|
let refresh_token = create_refresh_token(
|
||||||
|
&r.id, &r.role, permissions,
|
||||||
|
state.jwt_secret.expose_secret(),
|
||||||
|
config.auth.refresh_token_hours,
|
||||||
|
)?;
|
||||||
|
drop(config);
|
||||||
|
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
sqlx::query("UPDATE accounts SET last_login_at = $1 WHERE id = $2")
|
||||||
|
.bind(&now).bind(&r.id)
|
||||||
|
.execute(&state.db).await?;
|
||||||
|
let client_ip = addr.ip().to_string();
|
||||||
|
log_operation(&state.db, &r.id, "account.login", "account", &r.id, None, Some(&client_ip)).await?;
|
||||||
|
|
||||||
|
store_refresh_token(
|
||||||
|
&state.db, &r.id, &refresh_token,
|
||||||
|
state.jwt_secret.expose_secret(), 168,
|
||||||
|
).await?;
|
||||||
|
|
||||||
|
Ok(Json(LoginResponse {
|
||||||
|
token,
|
||||||
|
refresh_token,
|
||||||
|
account: AccountPublic {
|
||||||
|
id: r.id, username: r.username, email: r.email, display_name: r.display_name,
|
||||||
|
role: r.role, status: r.status, totp_enabled: r.totp_enabled, created_at: r.created_at,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/auth/refresh
|
||||||
|
/// 使用 refresh_token 换取新的 access + refresh token 对
|
||||||
|
/// refresh_token 一次性使用,使用后立即失效
|
||||||
|
pub async fn refresh(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Json(req): Json<RefreshRequest>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
// 1. 验证 refresh token 签名 (跳过过期检查,但有 7 天窗口限制)
|
||||||
|
let claims = verify_token_skip_expiry(&req.refresh_token, state.jwt_secret.expose_secret())?;
|
||||||
|
|
||||||
|
// 2. 确认是 refresh 类型 token
|
||||||
|
if claims.token_type != "refresh" {
|
||||||
|
return Err(SaasError::AuthError("无效的 refresh token".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let jti = claims.jti.as_deref()
|
||||||
|
.ok_or_else(|| SaasError::AuthError("refresh token 缺少 jti".into()))?;
|
||||||
|
|
||||||
|
// 3. 从 DB 查找 refresh token,确保未被使用
|
||||||
|
let row: Option<(String,)> = sqlx::query_as(
|
||||||
|
"SELECT account_id FROM refresh_tokens WHERE jti = $1 AND used_at IS NULL AND expires_at > $2"
|
||||||
|
)
|
||||||
|
.bind(jti)
|
||||||
|
.bind(&chrono::Utc::now().to_rfc3339())
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let token_account_id = row
|
||||||
|
.ok_or_else(|| SaasError::AuthError("refresh token 已使用、已过期或不存在".into()))?
|
||||||
|
.0;
|
||||||
|
|
||||||
|
// 4. 验证 token 中的 account_id 与 DB 中的一致
|
||||||
|
if token_account_id != claims.sub {
|
||||||
|
return Err(SaasError::AuthError("refresh token 账号不匹配".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 标记旧 refresh token 为已使用 (一次性)
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
sqlx::query("UPDATE refresh_tokens SET used_at = $1 WHERE jti = $2")
|
||||||
|
.bind(&now).bind(jti)
|
||||||
|
.execute(&state.db).await?;
|
||||||
|
|
||||||
|
// 6. 获取最新角色权限
|
||||||
|
let (role,): (String,) = sqlx::query_as(
|
||||||
|
"SELECT role FROM accounts WHERE id = $1 AND status = 'active'"
|
||||||
|
)
|
||||||
|
.bind(&claims.sub)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| SaasError::AuthError("账号不存在或已禁用".into()))?;
|
||||||
|
|
||||||
|
let permissions = get_role_permissions(&state.db, &state.role_permissions_cache, &role).await?;
|
||||||
|
|
||||||
|
// 7. 创建新的 access token + refresh token
|
||||||
|
let config = state.config.read().await;
|
||||||
|
let new_access = create_token(
|
||||||
|
&claims.sub, &role, permissions.clone(),
|
||||||
|
state.jwt_secret.expose_secret(),
|
||||||
|
config.auth.jwt_expiration_hours,
|
||||||
|
)?;
|
||||||
|
let new_refresh = create_refresh_token(
|
||||||
|
&claims.sub, &role, permissions.clone(),
|
||||||
|
state.jwt_secret.expose_secret(),
|
||||||
|
config.auth.refresh_token_hours,
|
||||||
|
)?;
|
||||||
|
drop(config);
|
||||||
|
|
||||||
|
// 8. 存储新 refresh token 到 DB
|
||||||
|
let new_claims = verify_token(&new_refresh, state.jwt_secret.expose_secret())?;
|
||||||
|
let new_jti = new_claims.jti.unwrap_or_default();
|
||||||
|
let new_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let refresh_expires = (chrono::Utc::now() + chrono::Duration::hours(168)).to_rfc3339();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO refresh_tokens (id, account_id, jti, token_hash, expires_at, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6)"
|
||||||
|
)
|
||||||
|
.bind(&new_id).bind(&claims.sub).bind(&new_jti)
|
||||||
|
.bind(sha256_hex(&new_refresh)).bind(&refresh_expires).bind(&now)
|
||||||
|
.execute(&state.db).await?;
|
||||||
|
|
||||||
|
// 9. 清理过期/已使用的 refresh tokens 已迁移到 Scheduler 定期执行
|
||||||
|
// 不再在每次 refresh 时阻塞请求
|
||||||
|
|
||||||
|
Ok(Json(serde_json::json!({
|
||||||
|
"token": new_access,
|
||||||
|
"refresh_token": new_refresh,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/auth/me — 返回当前认证用户的公开信息
|
||||||
|
pub async fn me(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
axum::extract::Extension(ctx): axum::extract::Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<AccountPublic>> {
|
||||||
|
let row: Option<AccountAuthRow> =
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, username, email, display_name, role, status, totp_enabled, created_at
|
||||||
|
FROM accounts WHERE id = $1"
|
||||||
|
)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let r = row.ok_or_else(|| SaasError::NotFound("账号不存在".into()))?;
|
||||||
|
|
||||||
|
Ok(Json(AccountPublic {
|
||||||
|
id: r.id, username: r.username, email: r.email, display_name: r.display_name,
|
||||||
|
role: r.role, status: r.status, totp_enabled: r.totp_enabled, created_at: r.created_at,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// PUT /api/v1/auth/password — 修改密码
|
||||||
|
pub async fn change_password(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
axum::extract::Extension(ctx): axum::extract::Extension<AuthContext>,
|
||||||
|
Json(req): Json<ChangePasswordRequest>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
if req.new_password.len() < 8 {
|
||||||
|
return Err(SaasError::InvalidInput("新密码至少 8 个字符".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取当前密码哈希
|
||||||
|
let (password_hash,): (String,) = sqlx::query_as(
|
||||||
|
"SELECT password_hash FROM accounts WHERE id = $1"
|
||||||
|
)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// 验证旧密码
|
||||||
|
if !verify_password(&req.old_password, &password_hash)? {
|
||||||
|
return Err(SaasError::AuthError("旧密码错误".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新密码
|
||||||
|
let new_hash = hash_password(&req.new_password)?;
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
sqlx::query("UPDATE accounts SET password_hash = $1, updated_at = $2 WHERE id = $3")
|
||||||
|
.bind(&new_hash)
|
||||||
|
.bind(&now)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
log_operation(&state.db, &ctx.account_id, "account.change_password", "account", &ctx.account_id,
|
||||||
|
None, ctx.client_ip.as_deref()).await?;
|
||||||
|
|
||||||
|
Ok(Json(serde_json::json!({"ok": true, "message": "密码修改成功"})))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn get_role_permissions(
|
||||||
|
db: &sqlx::PgPool,
|
||||||
|
cache: &dashmap::DashMap<String, Vec<String>>,
|
||||||
|
role: &str,
|
||||||
|
) -> SaasResult<Vec<String>> {
|
||||||
|
// Check cache first
|
||||||
|
if let Some(cached) = cache.get(role) {
|
||||||
|
return Ok(cached.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
let row: Option<(String,)> = sqlx::query_as(
|
||||||
|
"SELECT permissions FROM roles WHERE id = $1"
|
||||||
|
)
|
||||||
|
.bind(role)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let permissions_str = row
|
||||||
|
.ok_or_else(|| SaasError::Internal(format!("角色 {} 不存在", role)))?
|
||||||
|
.0;
|
||||||
|
|
||||||
|
let permissions: Vec<String> = serde_json::from_str(&permissions_str)?;
|
||||||
|
cache.insert(role.to_string(), permissions.clone());
|
||||||
|
Ok(permissions)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 检查权限 (admin:full 自动通过所有检查)
|
||||||
|
pub fn check_permission(ctx: &AuthContext, permission: &str) -> SaasResult<()> {
|
||||||
|
if ctx.permissions.contains(&"admin:full".to_string()) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if !ctx.permissions.contains(&permission.to_string()) {
|
||||||
|
return Err(SaasError::Forbidden(format!("需要 {} 权限", permission)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 记录操作日志
|
||||||
|
pub async fn log_operation(
|
||||||
|
db: &sqlx::PgPool,
|
||||||
|
account_id: &str,
|
||||||
|
action: &str,
|
||||||
|
target_type: &str,
|
||||||
|
target_id: &str,
|
||||||
|
details: Option<serde_json::Value>,
|
||||||
|
ip_address: Option<&str>,
|
||||||
|
) -> SaasResult<()> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO operation_logs (account_id, action, target_type, target_id, details, ip_address, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7)"
|
||||||
|
)
|
||||||
|
.bind(account_id)
|
||||||
|
.bind(action)
|
||||||
|
.bind(target_type)
|
||||||
|
.bind(target_id)
|
||||||
|
.bind(details.map(|d| d.to_string()))
|
||||||
|
.bind(ip_address)
|
||||||
|
.bind(&now)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 存储 refresh token 到 DB
|
||||||
|
async fn store_refresh_token(
|
||||||
|
db: &sqlx::PgPool,
|
||||||
|
account_id: &str,
|
||||||
|
refresh_token: &str,
|
||||||
|
secret: &str,
|
||||||
|
refresh_hours: i64,
|
||||||
|
) -> SaasResult<()> {
|
||||||
|
let claims = verify_token(refresh_token, secret)?;
|
||||||
|
let jti = claims.jti.unwrap_or_default();
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let expires_at = (chrono::Utc::now() + chrono::Duration::hours(refresh_hours)).to_rfc3339();
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO refresh_tokens (id, account_id, jti, token_hash, expires_at, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6)"
|
||||||
|
)
|
||||||
|
.bind(&id).bind(account_id).bind(&jti)
|
||||||
|
.bind(sha256_hex(refresh_token)).bind(&expires_at).bind(&now)
|
||||||
|
.execute(db).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 清理过期和已使用的 refresh tokens
|
||||||
|
/// 注意: 现已迁移到 Worker/Scheduler 定期执行,此函数保留作为备用
|
||||||
|
#[allow(dead_code)]
|
||||||
|
async fn cleanup_expired_refresh_tokens(db: &sqlx::PgPool) -> SaasResult<()> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
// 删除过期超过 30 天的已使用 token (减少 DB 膨胀)
|
||||||
|
sqlx::query(
|
||||||
|
"DELETE FROM refresh_tokens WHERE (used_at IS NOT NULL AND used_at < $1) OR (expires_at < $1)"
|
||||||
|
)
|
||||||
|
.bind(&now)
|
||||||
|
.execute(db).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SHA-256 hex digest
|
||||||
|
fn sha256_hex(input: &str) -> String {
|
||||||
|
use sha2::{Sha256, Digest};
|
||||||
|
hex::encode(Sha256::digest(input.as_bytes()))
|
||||||
|
}
|
||||||
194
crates/zclaw-saas/src/auth/jwt.rs
Normal file
194
crates/zclaw-saas/src/auth/jwt.rs
Normal file
@@ -0,0 +1,194 @@
|
|||||||
|
//! JWT Token 创建与验证
|
||||||
|
|
||||||
|
use chrono::{Duration, Utc};
|
||||||
|
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::error::SaasResult;
|
||||||
|
|
||||||
|
/// JWT Claims
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Claims {
|
||||||
|
/// JWT ID — 唯一标识,用于 token 追踪和吊销
|
||||||
|
pub jti: Option<String>,
|
||||||
|
pub sub: String,
|
||||||
|
pub role: String,
|
||||||
|
pub permissions: Vec<String>,
|
||||||
|
/// token 类型: "access" 或 "refresh"
|
||||||
|
#[serde(default = "default_token_type")]
|
||||||
|
pub token_type: String,
|
||||||
|
pub iat: i64,
|
||||||
|
pub exp: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_token_type() -> String {
|
||||||
|
"access".to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Claims {
|
||||||
|
pub fn new_access(account_id: &str, role: &str, permissions: Vec<String>, expiration_hours: i64) -> Self {
|
||||||
|
let now = Utc::now();
|
||||||
|
Self {
|
||||||
|
jti: Some(uuid::Uuid::new_v4().to_string()),
|
||||||
|
sub: account_id.to_string(),
|
||||||
|
role: role.to_string(),
|
||||||
|
permissions,
|
||||||
|
token_type: "access".to_string(),
|
||||||
|
iat: now.timestamp(),
|
||||||
|
exp: (now + Duration::hours(expiration_hours)).timestamp(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建 refresh token claims (有效期更长,用于一次性刷新)
|
||||||
|
pub fn new_refresh(account_id: &str, role: &str, permissions: Vec<String>, refresh_hours: i64) -> Self {
|
||||||
|
let now = Utc::now();
|
||||||
|
Self {
|
||||||
|
jti: Some(uuid::Uuid::new_v4().to_string()),
|
||||||
|
sub: account_id.to_string(),
|
||||||
|
role: role.to_string(),
|
||||||
|
permissions,
|
||||||
|
token_type: "refresh".to_string(),
|
||||||
|
iat: now.timestamp(),
|
||||||
|
exp: (now + Duration::hours(refresh_hours)).timestamp(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建 Access JWT Token
|
||||||
|
pub fn create_token(
|
||||||
|
account_id: &str,
|
||||||
|
role: &str,
|
||||||
|
permissions: Vec<String>,
|
||||||
|
secret: &str,
|
||||||
|
expiration_hours: i64,
|
||||||
|
) -> SaasResult<String> {
|
||||||
|
let claims = Claims::new_access(account_id, role, permissions, expiration_hours);
|
||||||
|
let token = encode(
|
||||||
|
&Header::default(),
|
||||||
|
&claims,
|
||||||
|
&EncodingKey::from_secret(secret.as_bytes()),
|
||||||
|
)?;
|
||||||
|
Ok(token)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建 Refresh JWT Token (独立 jti,有效期更长)
|
||||||
|
pub fn create_refresh_token(
|
||||||
|
account_id: &str,
|
||||||
|
role: &str,
|
||||||
|
permissions: Vec<String>,
|
||||||
|
secret: &str,
|
||||||
|
refresh_hours: i64,
|
||||||
|
) -> SaasResult<String> {
|
||||||
|
let claims = Claims::new_refresh(account_id, role, permissions, refresh_hours);
|
||||||
|
let token = encode(
|
||||||
|
&Header::default(),
|
||||||
|
&claims,
|
||||||
|
&EncodingKey::from_secret(secret.as_bytes()),
|
||||||
|
)?;
|
||||||
|
Ok(token)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 验证 JWT Token
|
||||||
|
pub fn verify_token(token: &str, secret: &str) -> SaasResult<Claims> {
|
||||||
|
let token_data = decode::<Claims>(
|
||||||
|
token,
|
||||||
|
&DecodingKey::from_secret(secret.as_bytes()),
|
||||||
|
&Validation::default(),
|
||||||
|
)?;
|
||||||
|
Ok(token_data.claims)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 验证 JWT Token 但跳过过期检查(仅用于 refresh token 刷新)
|
||||||
|
/// 限制: 原始 token 的 iat 必须在 7 天内
|
||||||
|
pub fn verify_token_skip_expiry(token: &str, secret: &str) -> SaasResult<Claims> {
|
||||||
|
let mut validation = Validation::default();
|
||||||
|
validation.validate_exp = false;
|
||||||
|
let token_data = decode::<Claims>(
|
||||||
|
token,
|
||||||
|
&DecodingKey::from_secret(secret.as_bytes()),
|
||||||
|
&validation,
|
||||||
|
)?;
|
||||||
|
let claims = &token_data.claims;
|
||||||
|
|
||||||
|
// 限制刷新窗口: token 签发时间必须在 7 天内
|
||||||
|
let now = Utc::now().timestamp();
|
||||||
|
let max_refresh_window = 7 * 24 * 3600; // 7 天
|
||||||
|
if now - claims.iat > max_refresh_window {
|
||||||
|
return Err(jsonwebtoken::errors::Error::from(
|
||||||
|
jsonwebtoken::errors::ErrorKind::ExpiredSignature
|
||||||
|
).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(token_data.claims)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Token 对: access token + refresh token
|
||||||
|
#[derive(Debug, serde::Serialize)]
|
||||||
|
pub struct TokenPair {
|
||||||
|
pub access_token: String,
|
||||||
|
pub refresh_token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建 access + refresh token 对
|
||||||
|
pub fn create_token_pair(
|
||||||
|
account_id: &str,
|
||||||
|
role: &str,
|
||||||
|
permissions: Vec<String>,
|
||||||
|
secret: &str,
|
||||||
|
access_hours: i64,
|
||||||
|
refresh_hours: i64,
|
||||||
|
) -> SaasResult<TokenPair> {
|
||||||
|
Ok(TokenPair {
|
||||||
|
access_token: create_token(account_id, role, permissions.clone(), secret, access_hours)?,
|
||||||
|
refresh_token: create_refresh_token(account_id, role, permissions, secret, refresh_hours)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const TEST_SECRET: &str = "test-secret-key";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_create_and_verify_token() {
|
||||||
|
let token = create_token(
|
||||||
|
"account-123", "admin",
|
||||||
|
vec!["model:read".to_string()],
|
||||||
|
TEST_SECRET, 24,
|
||||||
|
).unwrap();
|
||||||
|
|
||||||
|
let claims = verify_token(&token, TEST_SECRET).unwrap();
|
||||||
|
assert_eq!(claims.sub, "account-123");
|
||||||
|
assert_eq!(claims.role, "admin");
|
||||||
|
assert_eq!(claims.permissions, vec!["model:read"]);
|
||||||
|
assert!(claims.jti.is_some());
|
||||||
|
assert_eq!(claims.token_type, "access");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_invalid_token() {
|
||||||
|
let result = verify_token("invalid.token.here", TEST_SECRET);
|
||||||
|
assert!(result.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_wrong_secret() {
|
||||||
|
let token = create_token("account-123", "admin", vec![], TEST_SECRET, 24).unwrap();
|
||||||
|
let result = verify_token(&token, "wrong-secret");
|
||||||
|
assert!(result.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_refresh_token_has_different_jti() {
|
||||||
|
let access = create_token("acct-1", "user", vec![], TEST_SECRET, 1).unwrap();
|
||||||
|
let refresh = create_refresh_token("acct-1", "user", vec![], TEST_SECRET, 168).unwrap();
|
||||||
|
|
||||||
|
let access_claims = verify_token(&access, TEST_SECRET).unwrap();
|
||||||
|
let refresh_claims = verify_token(&refresh, TEST_SECRET).unwrap();
|
||||||
|
|
||||||
|
assert_ne!(access_claims.jti, refresh_claims.jti);
|
||||||
|
assert_eq!(access_claims.token_type, "access");
|
||||||
|
assert_eq!(refresh_claims.token_type, "refresh");
|
||||||
|
}
|
||||||
|
}
|
||||||
170
crates/zclaw-saas/src/auth/mod.rs
Normal file
170
crates/zclaw-saas/src/auth/mod.rs
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
//! 认证模块
|
||||||
|
|
||||||
|
pub mod jwt;
|
||||||
|
pub mod password;
|
||||||
|
pub mod types;
|
||||||
|
pub mod handlers;
|
||||||
|
pub mod totp;
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
extract::{Request, State},
|
||||||
|
http::header,
|
||||||
|
middleware::Next,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
extract::ConnectInfo,
|
||||||
|
};
|
||||||
|
use secrecy::ExposeSecret;
|
||||||
|
use crate::error::SaasError;
|
||||||
|
use crate::state::AppState;
|
||||||
|
use types::AuthContext;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
/// 通过 API Token 验证身份
|
||||||
|
///
|
||||||
|
/// 流程: SHA-256 哈希 → 查 api_tokens 表 → 检查有效期 → 获取关联账号角色权限 → 更新 last_used_at
|
||||||
|
async fn verify_api_token(state: &AppState, raw_token: &str, client_ip: Option<String>) -> Result<AuthContext, SaasError> {
|
||||||
|
use sha2::{Sha256, Digest};
|
||||||
|
|
||||||
|
let token_hash = hex::encode(Sha256::digest(raw_token.as_bytes()));
|
||||||
|
|
||||||
|
let row: Option<(String, Option<String>, String)> = sqlx::query_as(
|
||||||
|
"SELECT account_id, expires_at, permissions FROM api_tokens
|
||||||
|
WHERE token_hash = $1 AND revoked_at IS NULL"
|
||||||
|
)
|
||||||
|
.bind(&token_hash)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let (account_id, expires_at, permissions_json) = row
|
||||||
|
.ok_or(SaasError::Unauthorized)?;
|
||||||
|
|
||||||
|
// 检查是否过期
|
||||||
|
if let Some(ref exp) = expires_at {
|
||||||
|
let now = chrono::Utc::now();
|
||||||
|
if let Ok(exp_time) = chrono::DateTime::parse_from_rfc3339(exp) {
|
||||||
|
if now >= exp_time.with_timezone(&chrono::Utc) {
|
||||||
|
return Err(SaasError::Unauthorized);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询关联账号的角色
|
||||||
|
let (role,): (String,) = sqlx::query_as(
|
||||||
|
"SELECT role FROM accounts WHERE id = $1 AND status = 'active'"
|
||||||
|
)
|
||||||
|
.bind(&account_id)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?
|
||||||
|
.ok_or(SaasError::Unauthorized)?;
|
||||||
|
|
||||||
|
// 合并 token 权限与角色权限(去重)
|
||||||
|
let role_permissions = handlers::get_role_permissions(&state.db, &state.role_permissions_cache, &role).await?;
|
||||||
|
let token_permissions: Vec<String> = serde_json::from_str(&permissions_json).unwrap_or_default();
|
||||||
|
let mut permissions = role_permissions;
|
||||||
|
for p in token_permissions {
|
||||||
|
if !permissions.contains(&p) {
|
||||||
|
permissions.push(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 异步更新 last_used_at(不阻塞请求)
|
||||||
|
let db = state.db.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let _ = sqlx::query("UPDATE api_tokens SET last_used_at = $1 WHERE token_hash = $2")
|
||||||
|
.bind(&now).bind(&token_hash)
|
||||||
|
.execute(&db).await;
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(AuthContext {
|
||||||
|
account_id,
|
||||||
|
role,
|
||||||
|
permissions,
|
||||||
|
client_ip,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从请求中提取客户端 IP
|
||||||
|
fn extract_client_ip(req: &Request) -> Option<String> {
|
||||||
|
// 优先从 ConnectInfo 获取
|
||||||
|
if let Some(ConnectInfo(addr)) = req.extensions().get::<ConnectInfo<SocketAddr>>() {
|
||||||
|
return Some(addr.ip().to_string());
|
||||||
|
}
|
||||||
|
// 回退到 X-Forwarded-For / X-Real-IP
|
||||||
|
if let Some(forwarded) = req.headers()
|
||||||
|
.get("x-forwarded-for")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
{
|
||||||
|
return Some(forwarded.split(',').next()?.trim().to_string());
|
||||||
|
}
|
||||||
|
req.headers()
|
||||||
|
.get("x-real-ip")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 认证中间件: 从 JWT 或 API Token 提取身份
|
||||||
|
pub async fn auth_middleware(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
mut req: Request,
|
||||||
|
next: Next,
|
||||||
|
) -> Response {
|
||||||
|
let client_ip = extract_client_ip(&req);
|
||||||
|
let auth_header = req.headers()
|
||||||
|
.get(header::AUTHORIZATION)
|
||||||
|
.and_then(|v| v.to_str().ok());
|
||||||
|
|
||||||
|
let result = if let Some(auth) = auth_header {
|
||||||
|
if let Some(token) = auth.strip_prefix("Bearer ") {
|
||||||
|
if token.starts_with("zclaw_") {
|
||||||
|
// API Token 路径
|
||||||
|
verify_api_token(&state, token, client_ip.clone()).await
|
||||||
|
} else {
|
||||||
|
// JWT 路径
|
||||||
|
let verify_result = jwt::verify_token(token, state.jwt_secret.expose_secret());
|
||||||
|
verify_result
|
||||||
|
.map(|claims| AuthContext {
|
||||||
|
account_id: claims.sub,
|
||||||
|
role: claims.role,
|
||||||
|
permissions: claims.permissions,
|
||||||
|
client_ip,
|
||||||
|
})
|
||||||
|
.map_err(|_| SaasError::Unauthorized)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err(SaasError::Unauthorized)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err(SaasError::Unauthorized)
|
||||||
|
};
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(ctx) => {
|
||||||
|
req.extensions_mut().insert(ctx);
|
||||||
|
next.run(req).await
|
||||||
|
}
|
||||||
|
Err(e) => e.into_response(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 路由 (无需认证的端点)
|
||||||
|
pub fn routes() -> axum::Router<AppState> {
|
||||||
|
use axum::routing::post;
|
||||||
|
|
||||||
|
axum::Router::new()
|
||||||
|
.route("/api/v1/auth/register", post(handlers::register))
|
||||||
|
.route("/api/v1/auth/login", post(handlers::login))
|
||||||
|
.route("/api/v1/auth/refresh", post(handlers::refresh))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 需要认证的路由
|
||||||
|
pub fn protected_routes() -> axum::Router<AppState> {
|
||||||
|
use axum::routing::{get, post, put};
|
||||||
|
|
||||||
|
axum::Router::new()
|
||||||
|
.route("/api/v1/auth/me", get(handlers::me))
|
||||||
|
.route("/api/v1/auth/password", put(handlers::change_password))
|
||||||
|
.route("/api/v1/auth/totp/setup", post(totp::setup_totp))
|
||||||
|
.route("/api/v1/auth/totp/verify", post(totp::verify_totp))
|
||||||
|
.route("/api/v1/auth/totp/disable", post(totp::disable_totp))
|
||||||
|
}
|
||||||
48
crates/zclaw-saas/src/auth/password.rs
Normal file
48
crates/zclaw-saas/src/auth/password.rs
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
//! 密码哈希 (Argon2id)
|
||||||
|
|
||||||
|
use argon2::{
|
||||||
|
password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
|
||||||
|
Argon2,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::error::{SaasError, SaasResult};
|
||||||
|
|
||||||
|
/// 哈希密码
|
||||||
|
pub fn hash_password(password: &str) -> SaasResult<String> {
|
||||||
|
let salt = SaltString::generate(&mut OsRng);
|
||||||
|
let argon2 = Argon2::default();
|
||||||
|
let hash = argon2
|
||||||
|
.hash_password(password.as_bytes(), &salt)
|
||||||
|
.map_err(|e| SaasError::PasswordHash(e.to_string()))?;
|
||||||
|
Ok(hash.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 验证密码
|
||||||
|
pub fn verify_password(password: &str, hash: &str) -> SaasResult<bool> {
|
||||||
|
let parsed_hash = PasswordHash::new(hash)
|
||||||
|
.map_err(|e| SaasError::PasswordHash(e.to_string()))?;
|
||||||
|
Ok(Argon2::default()
|
||||||
|
.verify_password(password.as_bytes(), &parsed_hash)
|
||||||
|
.is_ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_hash_and_verify() {
|
||||||
|
let hash = hash_password("correct_password").unwrap();
|
||||||
|
assert!(verify_password("correct_password", &hash).unwrap());
|
||||||
|
assert!(!verify_password("wrong_password", &hash).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_different_hashes_for_same_password() {
|
||||||
|
let hash1 = hash_password("same_password").unwrap();
|
||||||
|
let hash2 = hash_password("same_password").unwrap();
|
||||||
|
assert_ne!(hash1, hash2);
|
||||||
|
assert!(verify_password("same_password", &hash1).unwrap());
|
||||||
|
assert!(verify_password("same_password", &hash2).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
242
crates/zclaw-saas/src/auth/totp.rs
Normal file
242
crates/zclaw-saas/src/auth/totp.rs
Normal file
@@ -0,0 +1,242 @@
|
|||||||
|
//! TOTP 双因素认证
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
extract::{Extension, State},
|
||||||
|
Json,
|
||||||
|
};
|
||||||
|
use crate::state::AppState;
|
||||||
|
use crate::error::{SaasError, SaasResult};
|
||||||
|
use crate::auth::types::AuthContext;
|
||||||
|
use crate::auth::handlers::log_operation;
|
||||||
|
use crate::crypto;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// TOTP 设置响应
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct TotpSetupResponse {
|
||||||
|
/// otpauth:// URI,用于扫码绑定
|
||||||
|
pub otpauth_uri: String,
|
||||||
|
/// Base32 编码的密钥(备用手动输入)
|
||||||
|
pub secret: String,
|
||||||
|
/// issuer 名称
|
||||||
|
pub issuer: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// TOTP 验证请求
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct TotpVerifyRequest {
|
||||||
|
pub code: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// TOTP 禁用请求
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct TotpDisableRequest {
|
||||||
|
pub password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 生成随机 Base32 密钥 (20 字节 = 32 字符 Base32)
|
||||||
|
fn generate_random_secret() -> String {
|
||||||
|
use rand::Rng;
|
||||||
|
let mut bytes = [0u8; 20];
|
||||||
|
rand::thread_rng().fill(&mut bytes);
|
||||||
|
data_encoding::BASE32.encode(&bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Base32 解码
|
||||||
|
fn base32_decode(data: &str) -> Option<Vec<u8>> {
|
||||||
|
data_encoding::BASE32.decode(data.as_bytes()).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 加密 TOTP secret (AES-256-GCM,随机 nonce)
|
||||||
|
/// 存储格式: enc:<base64(nonce||ciphertext)>
|
||||||
|
/// 委托给 crypto::encrypt_value 统一加密
|
||||||
|
fn encrypt_totp_secret(plaintext: &str, key: &[u8; 32]) -> Result<String, SaasError> {
|
||||||
|
crate::crypto::encrypt_value(plaintext, key)
|
||||||
|
.map_err(|e| SaasError::Internal(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解密 TOTP secret (仅支持新格式: 随机 nonce)
|
||||||
|
/// 旧的固定 nonce 格式应通过启动时迁移转换。
|
||||||
|
fn decrypt_totp_secret(encrypted: &str, key: &[u8; 32]) -> Result<String, SaasError> {
|
||||||
|
crate::crypto::decrypt_value(encrypted, key)
|
||||||
|
.map_err(|e| SaasError::Internal(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 生成 TOTP 密钥并返回 otpauth URI
|
||||||
|
pub fn generate_totp_secret(issuer: &str, account_name: &str) -> TotpSetupResponse {
|
||||||
|
let secret = generate_random_secret();
|
||||||
|
let otpauth_uri = format!(
|
||||||
|
"otpauth://totp/{}:{}?secret={}&issuer={}&algorithm=SHA1&digits=6&period=30",
|
||||||
|
urlencoding::encode(issuer),
|
||||||
|
urlencoding::encode(account_name),
|
||||||
|
secret,
|
||||||
|
urlencoding::encode(issuer),
|
||||||
|
);
|
||||||
|
|
||||||
|
TotpSetupResponse {
|
||||||
|
otpauth_uri,
|
||||||
|
secret,
|
||||||
|
issuer: issuer.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 验证 TOTP 6 位码
|
||||||
|
pub fn verify_totp_code(secret: &str, code: &str) -> bool {
|
||||||
|
let secret_bytes = match base32_decode(secret) {
|
||||||
|
Some(b) => b,
|
||||||
|
None => return false,
|
||||||
|
};
|
||||||
|
|
||||||
|
let totp = match totp_rs::TOTP::new(
|
||||||
|
totp_rs::Algorithm::SHA1,
|
||||||
|
6, // digits
|
||||||
|
1, // skew (允许 1 个周期偏差)
|
||||||
|
30, // step (秒)
|
||||||
|
secret_bytes,
|
||||||
|
) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
|
||||||
|
totp.check_current(code).unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/auth/totp/setup
|
||||||
|
/// 生成 TOTP 密钥并返回 otpauth URI
|
||||||
|
/// 用户扫码后需要调用 /verify 验证一个码才能激活
|
||||||
|
pub async fn setup_totp(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<TotpSetupResponse>> {
|
||||||
|
// 如果已启用 TOTP,先清除旧密钥
|
||||||
|
let (username,): (String,) = sqlx::query_as(
|
||||||
|
"SELECT username FROM accounts WHERE id = $1"
|
||||||
|
)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let config = state.config.read().await;
|
||||||
|
let setup = generate_totp_secret(&config.auth.totp_issuer, &username);
|
||||||
|
|
||||||
|
// 加密后存储密钥 (但不启用,需要 /verify 确认)
|
||||||
|
let enc_key = config.totp_encryption_key()
|
||||||
|
.map_err(|e| SaasError::Internal(e.to_string()))?;
|
||||||
|
let encrypted_secret = encrypt_totp_secret(&setup.secret, &enc_key)?;
|
||||||
|
|
||||||
|
sqlx::query("UPDATE accounts SET totp_secret = $1 WHERE id = $2")
|
||||||
|
.bind(&encrypted_secret)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
log_operation(&state.db, &ctx.account_id, "totp.setup", "account", &ctx.account_id,
|
||||||
|
None, ctx.client_ip.as_deref()).await?;
|
||||||
|
|
||||||
|
Ok(Json(setup))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/auth/totp/verify
|
||||||
|
/// 验证 TOTP 码并启用 2FA
|
||||||
|
pub async fn verify_totp(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<TotpVerifyRequest>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
let code = req.code.trim();
|
||||||
|
if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
|
||||||
|
return Err(SaasError::InvalidInput("TOTP 码必须是 6 位数字".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取存储的密钥
|
||||||
|
let (totp_secret,): (Option<String>,) = sqlx::query_as(
|
||||||
|
"SELECT totp_secret FROM accounts WHERE id = $1"
|
||||||
|
)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let encrypted_secret = totp_secret.ok_or_else(|| {
|
||||||
|
SaasError::InvalidInput("请先调用 /totp/setup 获取密钥".into())
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// 解密 secret (兼容旧的明文格式)
|
||||||
|
let config = state.config.read().await;
|
||||||
|
let enc_key = config.totp_encryption_key()
|
||||||
|
.map_err(|e| SaasError::Internal(e.to_string()))?;
|
||||||
|
let secret = if encrypted_secret.starts_with(crypto::ENCRYPTED_PREFIX) {
|
||||||
|
decrypt_totp_secret(&encrypted_secret, &enc_key)?
|
||||||
|
} else {
|
||||||
|
// 旧格式: 明文存储,需要迁移
|
||||||
|
encrypted_secret.clone()
|
||||||
|
};
|
||||||
|
|
||||||
|
if !verify_totp_code(&secret, code) {
|
||||||
|
return Err(SaasError::Totp("TOTP 码验证失败".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证成功 → 启用 TOTP,同时确保密钥已加密
|
||||||
|
let final_secret = if encrypted_secret.starts_with(crypto::ENCRYPTED_PREFIX) {
|
||||||
|
encrypted_secret
|
||||||
|
} else {
|
||||||
|
// 迁移: 加密旧明文密钥
|
||||||
|
encrypt_totp_secret(&secret, &enc_key)?
|
||||||
|
};
|
||||||
|
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
sqlx::query("UPDATE accounts SET totp_enabled = true, totp_secret = $1, updated_at = $2 WHERE id = $3")
|
||||||
|
.bind(&final_secret)
|
||||||
|
.bind(&now)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
log_operation(&state.db, &ctx.account_id, "totp.verify", "account", &ctx.account_id,
|
||||||
|
None, ctx.client_ip.as_deref()).await?;
|
||||||
|
|
||||||
|
Ok(Json(serde_json::json!({"ok": true, "totp_enabled": true, "message": "TOTP 已启用"})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/auth/totp/disable
|
||||||
|
/// 禁用 TOTP (需要密码确认)
|
||||||
|
pub async fn disable_totp(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<TotpDisableRequest>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
// 验证密码
|
||||||
|
let (password_hash,): (String,) = sqlx::query_as(
|
||||||
|
"SELECT password_hash FROM accounts WHERE id = $1"
|
||||||
|
)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if !crate::auth::password::verify_password(&req.password, &password_hash)? {
|
||||||
|
return Err(SaasError::AuthError("密码错误".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清除 TOTP
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
sqlx::query("UPDATE accounts SET totp_enabled = false, totp_secret = NULL, updated_at = $1 WHERE id = $2")
|
||||||
|
.bind(&now)
|
||||||
|
.bind(&ctx.account_id)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
log_operation(&state.db, &ctx.account_id, "totp.disable", "account", &ctx.account_id,
|
||||||
|
None, ctx.client_ip.as_deref()).await?;
|
||||||
|
|
||||||
|
Ok(Json(serde_json::json!({"ok": true, "totp_enabled": false, "message": "TOTP 已禁用"})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解密 TOTP secret (供 login handler 使用)
|
||||||
|
/// 返回解密后的明文 secret
|
||||||
|
pub fn decrypt_totp_for_login(encrypted_secret: &str, enc_key: &[u8; 32]) -> SaasResult<String> {
|
||||||
|
if encrypted_secret.starts_with(crypto::ENCRYPTED_PREFIX) {
|
||||||
|
decrypt_totp_secret(encrypted_secret, enc_key)
|
||||||
|
} else {
|
||||||
|
// 兼容旧的明文格式
|
||||||
|
Ok(encrypted_secret.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
63
crates/zclaw-saas/src/auth/types.rs
Normal file
63
crates/zclaw-saas/src/auth/types.rs
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
//! 认证相关类型
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// 登录请求
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct LoginRequest {
|
||||||
|
pub username: String,
|
||||||
|
pub password: String,
|
||||||
|
pub totp_code: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 登录响应
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct LoginResponse {
|
||||||
|
pub token: String,
|
||||||
|
pub refresh_token: String,
|
||||||
|
pub account: AccountPublic,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 注册请求
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct RegisterRequest {
|
||||||
|
pub username: String,
|
||||||
|
pub email: String,
|
||||||
|
pub password: String,
|
||||||
|
pub display_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 修改密码请求
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct ChangePasswordRequest {
|
||||||
|
pub old_password: String,
|
||||||
|
pub new_password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 公开账号信息 (无敏感数据)
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct AccountPublic {
|
||||||
|
pub id: String,
|
||||||
|
pub username: String,
|
||||||
|
pub email: String,
|
||||||
|
pub display_name: String,
|
||||||
|
pub role: String,
|
||||||
|
pub status: String,
|
||||||
|
pub totp_enabled: bool,
|
||||||
|
pub created_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 认证上下文 (注入到 request extensions)
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct AuthContext {
|
||||||
|
pub account_id: String,
|
||||||
|
pub role: String,
|
||||||
|
pub permissions: Vec<String>,
|
||||||
|
pub client_ip: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Token 刷新请求
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct RefreshRequest {
|
||||||
|
pub refresh_token: String,
|
||||||
|
}
|
||||||
51
crates/zclaw-saas/src/common.rs
Normal file
51
crates/zclaw-saas/src/common.rs
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
//! 公共类型和工具函数
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
/// 分页响应通用包装
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct PaginatedResponse<T: Serialize> {
|
||||||
|
pub items: Vec<T>,
|
||||||
|
pub total: i64,
|
||||||
|
pub page: u32,
|
||||||
|
pub page_size: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 分页上限
|
||||||
|
pub const MAX_PAGE_SIZE: u32 = 100;
|
||||||
|
|
||||||
|
/// 默认分页大小
|
||||||
|
pub const DEFAULT_PAGE_SIZE: u32 = 20;
|
||||||
|
|
||||||
|
/// 规范化分页参数,返回 (page, page_size, offset)
|
||||||
|
pub fn normalize_pagination(page: Option<u32>, page_size: Option<u32>) -> (u32, u32, i64) {
|
||||||
|
let p = page.unwrap_or(1).max(1);
|
||||||
|
let ps = page_size.unwrap_or(DEFAULT_PAGE_SIZE).min(MAX_PAGE_SIZE).max(1);
|
||||||
|
let offset = ((p - 1) * ps) as i64;
|
||||||
|
(p, ps, offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_normalize_pagination_defaults() {
|
||||||
|
let (page, size, offset) = normalize_pagination(None, None);
|
||||||
|
assert_eq!(page, 1);
|
||||||
|
assert_eq!(size, DEFAULT_PAGE_SIZE);
|
||||||
|
assert_eq!(offset, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_normalize_pagination_clamp() {
|
||||||
|
let (page, size, offset) = normalize_pagination(None, Some(999));
|
||||||
|
assert_eq!(size, MAX_PAGE_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_normalize_pagination_offset() {
|
||||||
|
let (page, size, offset) = normalize_pagination(Some(3), Some(10));
|
||||||
|
assert_eq!(offset, 20);
|
||||||
|
}
|
||||||
|
}
|
||||||
292
crates/zclaw-saas/src/config.rs
Normal file
292
crates/zclaw-saas/src/config.rs
Normal file
@@ -0,0 +1,292 @@
|
|||||||
|
//! SaaS 服务器配置
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use secrecy::{ExposeSecret, SecretString};
|
||||||
|
use sha2::Digest;
|
||||||
|
|
||||||
|
/// SaaS 服务器完整配置
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct SaaSConfig {
|
||||||
|
pub server: ServerConfig,
|
||||||
|
pub database: DatabaseConfig,
|
||||||
|
pub auth: AuthConfig,
|
||||||
|
pub relay: RelayConfig,
|
||||||
|
#[serde(default)]
|
||||||
|
pub rate_limit: RateLimitConfig,
|
||||||
|
#[serde(default)]
|
||||||
|
pub scheduler: SchedulerConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Scheduler 定时任务配置
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct SchedulerConfig {
|
||||||
|
#[serde(default)]
|
||||||
|
pub jobs: Vec<JobConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 单个定时任务配置
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct JobConfig {
|
||||||
|
pub name: String,
|
||||||
|
/// 间隔时间,支持 "5m", "1h", "24h", "30s" 格式
|
||||||
|
pub interval: String,
|
||||||
|
/// 对应的 Worker 名称
|
||||||
|
pub task: String,
|
||||||
|
/// 传递给 Worker 的参数(JSON 格式)
|
||||||
|
#[serde(default)]
|
||||||
|
pub args: Option<serde_json::Value>,
|
||||||
|
/// 是否在启动时立即执行
|
||||||
|
#[serde(default)]
|
||||||
|
pub run_on_start: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for SchedulerConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { jobs: Vec::new() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 服务器配置
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ServerConfig {
|
||||||
|
#[serde(default = "default_host")]
|
||||||
|
pub host: String,
|
||||||
|
#[serde(default = "default_port")]
|
||||||
|
pub port: u16,
|
||||||
|
#[serde(default)]
|
||||||
|
pub cors_origins: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 数据库配置
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct DatabaseConfig {
|
||||||
|
#[serde(default = "default_db_url")]
|
||||||
|
pub url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 认证配置
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct AuthConfig {
|
||||||
|
#[serde(default = "default_jwt_hours")]
|
||||||
|
pub jwt_expiration_hours: i64,
|
||||||
|
#[serde(default = "default_totp_issuer")]
|
||||||
|
pub totp_issuer: String,
|
||||||
|
/// Refresh Token 有效期 (小时), 默认 168 小时 = 7 天
|
||||||
|
#[serde(default = "default_refresh_hours")]
|
||||||
|
pub refresh_token_hours: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 中转服务配置
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RelayConfig {
|
||||||
|
#[serde(default = "default_max_queue")]
|
||||||
|
pub max_queue_size: usize,
|
||||||
|
/// 每个 Provider 最大并发请求数 (预留,当前由 max_queue_size 控制)
|
||||||
|
#[serde(default = "default_max_concurrent")]
|
||||||
|
pub max_concurrent_per_provider: usize,
|
||||||
|
/// 批量窗口间隔 (预留,用于请求合并优化)
|
||||||
|
#[serde(default = "default_batch_window")]
|
||||||
|
pub batch_window_ms: u64,
|
||||||
|
#[serde(default = "default_retry_delay")]
|
||||||
|
pub retry_delay_ms: u64,
|
||||||
|
#[serde(default = "default_max_attempts")]
|
||||||
|
pub max_attempts: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_host() -> String { "0.0.0.0".into() }
|
||||||
|
fn default_port() -> u16 { 8080 }
|
||||||
|
fn default_db_url() -> String { "postgres://localhost:5432/zclaw".into() }
|
||||||
|
fn default_jwt_hours() -> i64 { 24 }
|
||||||
|
fn default_totp_issuer() -> String { "ZCLAW SaaS".into() }
|
||||||
|
fn default_refresh_hours() -> i64 { 168 }
|
||||||
|
fn default_max_queue() -> usize { 1000 }
|
||||||
|
fn default_max_concurrent() -> usize { 5 }
|
||||||
|
fn default_batch_window() -> u64 { 50 }
|
||||||
|
fn default_retry_delay() -> u64 { 1000 }
|
||||||
|
fn default_max_attempts() -> u32 { 3 }
|
||||||
|
|
||||||
|
/// 速率限制配置
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RateLimitConfig {
|
||||||
|
/// 每分钟最大请求数 (滑动窗口)
|
||||||
|
#[serde(default = "default_rpm")]
|
||||||
|
pub requests_per_minute: u32,
|
||||||
|
/// 突发允许的额外请求数
|
||||||
|
#[serde(default = "default_burst")]
|
||||||
|
pub burst: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_rpm() -> u32 { 60 }
|
||||||
|
fn default_burst() -> u32 { 10 }
|
||||||
|
|
||||||
|
impl Default for RateLimitConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
requests_per_minute: default_rpm(),
|
||||||
|
burst: default_burst(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for SaaSConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
server: ServerConfig::default(),
|
||||||
|
database: DatabaseConfig::default(),
|
||||||
|
auth: AuthConfig::default(),
|
||||||
|
relay: RelayConfig::default(),
|
||||||
|
rate_limit: RateLimitConfig::default(),
|
||||||
|
scheduler: SchedulerConfig::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ServerConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
host: default_host(),
|
||||||
|
port: default_port(),
|
||||||
|
cors_origins: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for DatabaseConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { url: default_db_url() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for AuthConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
jwt_expiration_hours: default_jwt_hours(),
|
||||||
|
totp_issuer: default_totp_issuer(),
|
||||||
|
refresh_token_hours: default_refresh_hours(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for RelayConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
max_queue_size: default_max_queue(),
|
||||||
|
max_concurrent_per_provider: default_max_concurrent(),
|
||||||
|
batch_window_ms: default_batch_window(),
|
||||||
|
retry_delay_ms: default_retry_delay(),
|
||||||
|
max_attempts: default_max_attempts(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SaaSConfig {
|
||||||
|
/// 加载配置文件,优先级: ZCLAW_SAAS_CONFIG > ZCLAW_ENV > ./saas-config.toml
|
||||||
|
///
|
||||||
|
/// ZCLAW_ENV 环境选择:
|
||||||
|
/// development → config/saas-development.toml
|
||||||
|
/// production → config/saas-production.toml
|
||||||
|
/// test → config/saas-test.toml
|
||||||
|
///
|
||||||
|
/// ZCLAW_SAAS_CONFIG 指定精确路径(最高优先级)
|
||||||
|
pub fn load() -> anyhow::Result<Self> {
|
||||||
|
let config_path = if let Ok(path) = std::env::var("ZCLAW_SAAS_CONFIG") {
|
||||||
|
PathBuf::from(path)
|
||||||
|
} else if let Ok(env) = std::env::var("ZCLAW_ENV") {
|
||||||
|
let filename = format!("config/saas-{}.toml", env);
|
||||||
|
let path = PathBuf::from(&filename);
|
||||||
|
if !path.exists() {
|
||||||
|
anyhow::bail!(
|
||||||
|
"ZCLAW_ENV={} 指定的配置文件 {} 不存在",
|
||||||
|
env, filename
|
||||||
|
);
|
||||||
|
}
|
||||||
|
tracing::info!("Loading config for environment: {}", env);
|
||||||
|
path
|
||||||
|
} else {
|
||||||
|
PathBuf::from("saas-config.toml")
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut config = if config_path.exists() {
|
||||||
|
let content = std::fs::read_to_string(&config_path)?;
|
||||||
|
toml::from_str(&content)?
|
||||||
|
} else {
|
||||||
|
tracing::warn!("Config file {:?} not found, using defaults", config_path);
|
||||||
|
SaaSConfig::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
// 环境变量覆盖数据库 URL (避免在配置文件中存储密码)
|
||||||
|
if let Ok(db_url) = std::env::var("ZCLAW_DATABASE_URL") {
|
||||||
|
config.database.url = db_url;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 获取 JWT 密钥 (从环境变量或生成临时值)
|
||||||
|
/// 生产环境必须设置 ZCLAW_SAAS_JWT_SECRET
|
||||||
|
pub fn jwt_secret(&self) -> anyhow::Result<SecretString> {
|
||||||
|
let is_dev = std::env::var("ZCLAW_SAAS_DEV")
|
||||||
|
.map(|v| v == "true" || v == "1")
|
||||||
|
.unwrap_or(false);
|
||||||
|
|
||||||
|
match std::env::var("ZCLAW_SAAS_JWT_SECRET") {
|
||||||
|
Ok(secret) => Ok(SecretString::from(secret)),
|
||||||
|
Err(_) => {
|
||||||
|
if is_dev {
|
||||||
|
tracing::warn!("ZCLAW_SAAS_JWT_SECRET not set, using development default (INSECURE)");
|
||||||
|
Ok(SecretString::from("zclaw-dev-only-secret-do-not-use-in-prod".to_string()))
|
||||||
|
} else {
|
||||||
|
anyhow::bail!(
|
||||||
|
"ZCLAW_SAAS_JWT_SECRET 环境变量未设置。\
|
||||||
|
请设置一个强随机密钥 (至少 32 字符)。\
|
||||||
|
开发环境可设置 ZCLAW_SAAS_DEV=true 使用默认值。"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 获取 API Key 加密密钥 (复用 TOTP 加密密钥)
|
||||||
|
pub fn api_key_encryption_key(&self) -> anyhow::Result<[u8; 32]> {
|
||||||
|
self.totp_encryption_key()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 获取 TOTP 加密密钥 (AES-256-GCM, 32 字节)
|
||||||
|
/// 从 ZCLAW_TOTP_ENCRYPTION_KEY 环境变量加载 (hex 编码的 64 字符)
|
||||||
|
/// 开发环境使用默认值 (不安全)
|
||||||
|
pub fn totp_encryption_key(&self) -> anyhow::Result<[u8; 32]> {
|
||||||
|
let is_dev = std::env::var("ZCLAW_SAAS_DEV")
|
||||||
|
.map(|v| v == "true" || v == "1")
|
||||||
|
.unwrap_or(false);
|
||||||
|
|
||||||
|
match std::env::var("ZCLAW_TOTP_ENCRYPTION_KEY") {
|
||||||
|
Ok(hex_key) => {
|
||||||
|
if hex_key.len() != 64 {
|
||||||
|
anyhow::bail!("ZCLAW_TOTP_ENCRYPTION_KEY 必须是 64 个十六进制字符 (32 字节)");
|
||||||
|
}
|
||||||
|
let mut key = [0u8; 32];
|
||||||
|
for i in 0..32 {
|
||||||
|
key[i] = u8::from_str_radix(&hex_key[i*2..i*2+2], 16)
|
||||||
|
.map_err(|_| anyhow::anyhow!("ZCLAW_TOTP_ENCRYPTION_KEY 包含无效的十六进制字符"))?;
|
||||||
|
}
|
||||||
|
Ok(key)
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
if is_dev {
|
||||||
|
tracing::warn!("ZCLAW_TOTP_ENCRYPTION_KEY not set, using development default (INSECURE)");
|
||||||
|
// 开发环境使用固定密钥
|
||||||
|
let mut key = [0u8; 32];
|
||||||
|
key.copy_from_slice(b"zclaw-dev-totp-encrypt-key-32b!x");
|
||||||
|
Ok(key)
|
||||||
|
} else {
|
||||||
|
// 生产环境: 使用 JWT 密钥的 SHA-256 哈希作为加密密钥
|
||||||
|
tracing::warn!("ZCLAW_TOTP_ENCRYPTION_KEY not set, deriving from JWT secret");
|
||||||
|
let jwt = self.jwt_secret()?;
|
||||||
|
let hash = sha2::Sha256::digest(jwt.expose_secret().as_bytes());
|
||||||
|
Ok(hash.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
103
crates/zclaw-saas/src/crypto.rs
Normal file
103
crates/zclaw-saas/src/crypto.rs
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
//! 通用加密工具 (AES-256-GCM)
|
||||||
|
//!
|
||||||
|
//! 提供 API Key、TOTP secret 等敏感数据的加密/解密。
|
||||||
|
//! 存储格式: `enc:<base64(nonce(12 bytes) || ciphertext)>`
|
||||||
|
|
||||||
|
use aes_gcm::aead::{Aead, KeyInit, OsRng};
|
||||||
|
use aes_gcm::aead::rand_core::RngCore;
|
||||||
|
use aes_gcm::{Aes256Gcm, Nonce};
|
||||||
|
use crate::error::{SaasError, SaasResult};
|
||||||
|
|
||||||
|
/// 加密值的前缀标识
|
||||||
|
pub const ENCRYPTED_PREFIX: &str = "enc:";
|
||||||
|
|
||||||
|
/// AES-256-GCM nonce 长度 (12 字节)
|
||||||
|
const NONCE_SIZE: usize = 12;
|
||||||
|
|
||||||
|
/// 加密明文值 (AES-256-GCM, 随机 nonce)
|
||||||
|
///
|
||||||
|
/// 返回格式: `enc:<base64(nonce(12 bytes) || ciphertext)>`
|
||||||
|
/// 每次加密使用随机 nonce,相同明文产生不同密文。
|
||||||
|
pub fn encrypt_value(plaintext: &str, key: &[u8; 32]) -> SaasResult<String> {
|
||||||
|
let cipher = Aes256Gcm::new_from_slice(key)
|
||||||
|
.map_err(|e| SaasError::Encryption(format!("加密初始化失败: {}", e)))?;
|
||||||
|
|
||||||
|
let mut nonce_bytes = [0u8; NONCE_SIZE];
|
||||||
|
OsRng.fill_bytes(&mut nonce_bytes);
|
||||||
|
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||||
|
|
||||||
|
let ciphertext = cipher.encrypt(nonce, plaintext.as_bytes())
|
||||||
|
.map_err(|e| SaasError::Encryption(format!("加密失败: {}", e)))?;
|
||||||
|
|
||||||
|
let mut combined = nonce_bytes.to_vec();
|
||||||
|
combined.extend_from_slice(&ciphertext);
|
||||||
|
|
||||||
|
Ok(format!("{}{}", ENCRYPTED_PREFIX, data_encoding::BASE64.encode(&combined)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解密 `enc:` 前缀的加密值
|
||||||
|
///
|
||||||
|
/// 仅支持新格式 (随机 nonce),不支持旧格式 (固定 nonce)。
|
||||||
|
/// 旧格式数据应通过一次性迁移函数转换。
|
||||||
|
pub fn decrypt_value(encrypted: &str, key: &[u8; 32]) -> SaasResult<String> {
|
||||||
|
let encoded = encrypted.strip_prefix(ENCRYPTED_PREFIX)
|
||||||
|
.ok_or_else(|| SaasError::Encryption("加密值格式无效 (缺少 enc: 前缀)".into()))?;
|
||||||
|
|
||||||
|
let raw = data_encoding::BASE64.decode(encoded.as_bytes())
|
||||||
|
.map_err(|_| SaasError::Encryption("加密值 Base64 解码失败".into()))?;
|
||||||
|
|
||||||
|
if raw.len() <= NONCE_SIZE {
|
||||||
|
return Err(SaasError::Encryption("加密值数据不完整".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let cipher = Aes256Gcm::new_from_slice(key)
|
||||||
|
.map_err(|e| SaasError::Encryption(format!("解密初始化失败: {}", e)))?;
|
||||||
|
|
||||||
|
let (nonce_bytes, ciphertext) = raw.split_at(NONCE_SIZE);
|
||||||
|
let nonce = Nonce::from_slice(nonce_bytes);
|
||||||
|
|
||||||
|
let plaintext = cipher.decrypt(nonce, ciphertext)
|
||||||
|
.map_err(|_| SaasError::Encryption("解密失败 (密钥可能已变更)".into()))?;
|
||||||
|
|
||||||
|
String::from_utf8(plaintext)
|
||||||
|
.map_err(|_| SaasError::Encryption("解密后数据无效 UTF-8".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 检查值是否已加密 (以 `enc:` 开头)
|
||||||
|
pub fn is_encrypted(value: &str) -> bool {
|
||||||
|
value.starts_with(ENCRYPTED_PREFIX)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 批量迁移: 将旧的固定 nonce 加密值重新加密为随机 nonce 格式
|
||||||
|
///
|
||||||
|
/// 输入为旧格式 (固定 nonce `zclaw_totp_nce`) 加密的 base64 数据,
|
||||||
|
/// 输出为新格式 `enc:<base64(random_nonce || ciphertext)>`。
|
||||||
|
pub fn re_encrypt_from_legacy(legacy_base64: &str, legacy_key: &[u8; 32], new_key: &[u8; 32]) -> SaasResult<String> {
|
||||||
|
// 先用旧 nonce 解密
|
||||||
|
let cipher = Aes256Gcm::new_from_slice(legacy_key)
|
||||||
|
.map_err(|e| SaasError::Encryption(format!("解密初始化失败: {}", e)))?;
|
||||||
|
|
||||||
|
let raw = data_encoding::BASE64.decode(legacy_base64.as_bytes())
|
||||||
|
.or_else(|_| data_encoding::BASE32.decode(legacy_base64.as_bytes()))
|
||||||
|
.map_err(|_| SaasError::Encryption("旧格式 Base64/Base32 解码失败".into()))?;
|
||||||
|
|
||||||
|
// 尝试新格式 (前 12 字节为 nonce)
|
||||||
|
if raw.len() > NONCE_SIZE {
|
||||||
|
let (nonce_bytes, ciphertext) = raw.split_at(NONCE_SIZE);
|
||||||
|
let nonce = Nonce::from_slice(nonce_bytes);
|
||||||
|
if let Ok(plaintext_bytes) = cipher.decrypt(nonce, ciphertext) {
|
||||||
|
let plaintext = String::from_utf8(plaintext_bytes)
|
||||||
|
.map_err(|_| SaasError::Encryption("旧格式解密后数据无效".into()))?;
|
||||||
|
return encrypt_value(&plaintext, new_key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回退到旧格式: 固定 nonce
|
||||||
|
let legacy_nonce = Nonce::from_slice(b"zclaw_totp_nce");
|
||||||
|
let plaintext_bytes = cipher.decrypt(legacy_nonce, raw.as_ref())
|
||||||
|
.map_err(|_| SaasError::Encryption("旧格式解密失败".into()))?;
|
||||||
|
let plaintext = String::from_utf8(plaintext_bytes)
|
||||||
|
.map_err(|_| SaasError::Encryption("旧格式解密后数据无效".into()))?;
|
||||||
|
|
||||||
|
encrypt_value(&plaintext, new_key)
|
||||||
|
}
|
||||||
259
crates/zclaw-saas/src/db.rs
Normal file
259
crates/zclaw-saas/src/db.rs
Normal file
@@ -0,0 +1,259 @@
|
|||||||
|
//! 数据库初始化与 Schema (PostgreSQL)
|
||||||
|
|
||||||
|
use sqlx::postgres::PgPoolOptions;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use crate::error::SaasResult;
|
||||||
|
|
||||||
|
const SCHEMA_VERSION: i32 = 6;
|
||||||
|
|
||||||
|
/// 初始化数据库
|
||||||
|
pub async fn init_db(database_url: &str) -> SaasResult<PgPool> {
|
||||||
|
let pool = PgPoolOptions::new()
|
||||||
|
.max_connections(50)
|
||||||
|
.min_connections(5)
|
||||||
|
.acquire_timeout(std::time::Duration::from_secs(10))
|
||||||
|
.idle_timeout(std::time::Duration::from_secs(300))
|
||||||
|
.max_lifetime(std::time::Duration::from_secs(1800))
|
||||||
|
.connect(database_url)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
run_migrations(&pool).await?;
|
||||||
|
seed_admin_account(&pool).await?;
|
||||||
|
seed_builtin_prompts(&pool).await?;
|
||||||
|
tracing::info!("Database initialized (schema v{})", SCHEMA_VERSION);
|
||||||
|
Ok(pool)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 执行数据库迁移
|
||||||
|
///
|
||||||
|
/// 优先使用 migrations/ 目录下的 SQL 文件(支持 TIMESTAMPTZ),
|
||||||
|
/// 如果不存在则回退到内联 schema(向后兼容 TEXT 时间戳的旧数据库)。
|
||||||
|
async fn run_migrations(pool: &PgPool) -> SaasResult<()> {
|
||||||
|
// 检查是否已有 schema(已有的数据库保持 TEXT 类型不变)
|
||||||
|
let existing_version: Option<i32> = sqlx::query_scalar(
|
||||||
|
"SELECT version FROM saas_schema_version ORDER BY version DESC LIMIT 1"
|
||||||
|
)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await
|
||||||
|
.unwrap_or(None);
|
||||||
|
|
||||||
|
match existing_version {
|
||||||
|
Some(v) if v >= SCHEMA_VERSION => {
|
||||||
|
tracing::debug!("Schema already at v{}, no migration needed", v);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Some(v) => {
|
||||||
|
tracing::info!("Schema at v{}, upgrading to v{}", v, SCHEMA_VERSION);
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
tracing::info!("No schema found, running initial migration");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试从 migrations 目录加载 SQL 文件
|
||||||
|
let migrations_dir = std::path::Path::new("crates/zclaw-saas/migrations");
|
||||||
|
if migrations_dir.exists() {
|
||||||
|
run_migration_files(pool, migrations_dir).await?;
|
||||||
|
} else {
|
||||||
|
// 回退:使用 migrations/ 的替代路径(开发环境可能在项目根目录)
|
||||||
|
let alt_dir = std::path::Path::new("migrations");
|
||||||
|
if alt_dir.exists() {
|
||||||
|
run_migration_files(pool, alt_dir).await?;
|
||||||
|
} else {
|
||||||
|
tracing::warn!("No migrations directory found, schema may be incomplete");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新 schema 版本
|
||||||
|
sqlx::query("INSERT INTO saas_schema_version (version) VALUES ($1) ON CONFLICT DO NOTHING")
|
||||||
|
.bind(SCHEMA_VERSION)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Seed roles
|
||||||
|
seed_roles(pool).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从目录加载并执行迁移文件(按文件名排序)
|
||||||
|
async fn run_migration_files(pool: &PgPool, dir: &std::path::Path) -> SaasResult<()> {
|
||||||
|
let mut entries: Vec<std::path::PathBuf> = std::fs::read_dir(dir)?
|
||||||
|
.filter_map(|e| e.ok())
|
||||||
|
.map(|e| e.path())
|
||||||
|
.filter(|p| p.extension().map(|ext| ext == "sql").unwrap_or(false))
|
||||||
|
.collect();
|
||||||
|
entries.sort();
|
||||||
|
|
||||||
|
for path in &entries {
|
||||||
|
let filename = path.file_name().unwrap_or_default().to_string_lossy();
|
||||||
|
tracing::info!("Running migration: {}", filename);
|
||||||
|
let content = std::fs::read_to_string(path)?;
|
||||||
|
for stmt in content.split(';') {
|
||||||
|
let trimmed = stmt.trim();
|
||||||
|
if !trimmed.is_empty() && !trimmed.starts_with("--") {
|
||||||
|
sqlx::query(trimmed).execute(pool).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seed 角色数据
|
||||||
|
async fn seed_roles(pool: &PgPool) -> SaasResult<()> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
sqlx::query(
|
||||||
|
r#"INSERT INTO roles (id, name, description, permissions, is_system, created_at, updated_at)
|
||||||
|
VALUES
|
||||||
|
('super_admin', '超级管理员', '拥有所有权限', '["admin:full","account:admin","provider:manage","model:manage","relay:admin","config:write","prompt:read","prompt:write","prompt:publish","prompt:admin"]', TRUE, $1, $1),
|
||||||
|
('admin', '管理员', '管理账号和配置', '["account:read","account:admin","provider:manage","model:read","model:manage","relay:use","relay:admin","config:read","config:write","prompt:read","prompt:write","prompt:publish"]', TRUE, $1, $1),
|
||||||
|
('user', '普通用户', '基础使用权限', '["model:read","relay:use","config:read","prompt:read"]', TRUE, $1, $1)
|
||||||
|
ON CONFLICT (id) DO NOTHING"#
|
||||||
|
)
|
||||||
|
.bind(&now)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 如果 accounts 表为空且环境变量已设置,自动创建 super_admin 账号
|
||||||
|
/// 或者更新现有 admin 用户的角色为 super_admin
|
||||||
|
pub async fn seed_admin_account(pool: &PgPool) -> SaasResult<()> {
|
||||||
|
let admin_username = std::env::var("ZCLAW_ADMIN_USERNAME")
|
||||||
|
.unwrap_or_else(|_| "admin".to_string());
|
||||||
|
|
||||||
|
// 检查是否设置了管理员密码
|
||||||
|
let admin_password = match std::env::var("ZCLAW_ADMIN_PASSWORD") {
|
||||||
|
Ok(pwd) => pwd,
|
||||||
|
Err(_) => {
|
||||||
|
// 没有设置密码,尝试更新现有 admin 用户的角色
|
||||||
|
let result = sqlx::query(
|
||||||
|
"UPDATE accounts SET role = 'super_admin' WHERE username = $1 AND role != 'super_admin'"
|
||||||
|
)
|
||||||
|
.bind(&admin_username)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if result.rows_affected() > 0 {
|
||||||
|
tracing::info!("已将用户 {} 的角色更新为 super_admin", admin_username);
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 检查 admin 用户是否已存在
|
||||||
|
let existing: Option<(String,)> = sqlx::query_as(
|
||||||
|
"SELECT id FROM accounts WHERE username = $1"
|
||||||
|
)
|
||||||
|
.bind(&admin_username)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if let Some((account_id,)) = existing {
|
||||||
|
// 更新现有用户的密码和角色
|
||||||
|
use crate::auth::password::hash_password;
|
||||||
|
let password_hash = hash_password(&admin_password)?;
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE accounts SET password_hash = $1, role = 'super_admin', updated_at = $2 WHERE id = $3"
|
||||||
|
)
|
||||||
|
.bind(&password_hash)
|
||||||
|
.bind(&now)
|
||||||
|
.bind(&account_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!("已更新用户 {} 的密码和角色为 super_admin", admin_username);
|
||||||
|
} else {
|
||||||
|
// 创建新的 super_admin 账号
|
||||||
|
use crate::auth::password::hash_password;
|
||||||
|
let password_hash = hash_password(&admin_password)?;
|
||||||
|
let account_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let email = format!("{}@zclaw.local", admin_username);
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO accounts (id, username, email, password_hash, display_name, role, status, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, 'super_admin', 'active', $6, $6)"
|
||||||
|
)
|
||||||
|
.bind(&account_id)
|
||||||
|
.bind(&admin_username)
|
||||||
|
.bind(&email)
|
||||||
|
.bind(&password_hash)
|
||||||
|
.bind(&admin_username)
|
||||||
|
.bind(&now)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!("自动创建 super_admin 账号: username={}, email={}", admin_username, email);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 种子化内置提示词模板(仅当表为空时)
|
||||||
|
async fn seed_builtin_prompts(pool: &PgPool) -> SaasResult<()> {
|
||||||
|
let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM prompt_templates")
|
||||||
|
.fetch_one(pool).await?;
|
||||||
|
|
||||||
|
if count.0 > 0 {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
// reflection 提示词
|
||||||
|
let reflection_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let reflection_ver_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO prompt_templates (id, name, category, description, source, current_version, status, created_at, updated_at)
|
||||||
|
VALUES ($1, 'reflection', 'builtin_system', 'Agent 自我反思引擎', 'builtin', 1, 'active', $2, $2)"
|
||||||
|
).bind(&reflection_id).bind(&now).execute(pool).await?;
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO prompt_versions (id, template_id, version, system_prompt, user_prompt_template, variables, changelog, min_app_version, created_at)
|
||||||
|
VALUES ($1, $2, 1, $3, $4, '[]', '初始版本', NULL, $5)"
|
||||||
|
).bind(&reflection_ver_id).bind(&reflection_id)
|
||||||
|
.bind("你是一个 AI Agent 的自我反思引擎。分析最近的对话历史,识别行为模式,并生成改进建议。\n\n输出 JSON 格式:\n{\n \"patterns\": [\n {\n \"observation\": \"观察到的模式描述\",\n \"frequency\": 数字,\n \"sentiment\": \"positive/negative/neutral\",\n \"evidence\": [\"证据1\", \"证据2\"]\n }\n ],\n \"improvements\": [\n {\n \"area\": \"改进领域\",\n \"suggestion\": \"具体建议\",\n \"priority\": \"high/medium/low\"\n }\n ],\n \"identityProposals\": []\n}")
|
||||||
|
.bind("分析以下对话历史,进行自我反思:\n\n{{context}}\n\n请识别行为模式(积极和消极),并提供具体的改进建议。")
|
||||||
|
.bind(&now).execute(pool).await?;
|
||||||
|
|
||||||
|
// compaction 提示词
|
||||||
|
let compaction_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let compaction_ver_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO prompt_templates (id, name, category, description, source, current_version, status, created_at, updated_at)
|
||||||
|
VALUES ($1, 'compaction', 'builtin_compaction', '对话上下文压缩', 'builtin', 1, 'active', $2, $2)"
|
||||||
|
).bind(&compaction_id).bind(&now).execute(pool).await?;
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO prompt_versions (id, template_id, version, system_prompt, user_prompt_template, variables, changelog, min_app_version, created_at)
|
||||||
|
VALUES ($1, $2, 1, $3, $4, '[]', '初始版本', NULL, $5)"
|
||||||
|
).bind(&compaction_ver_id).bind(&compaction_id)
|
||||||
|
.bind("你是一个对话摘要专家。将长对话压缩为简洁的摘要,保留关键信息。\n\n要求:\n1. 保留所有重要决策和结论\n2. 保留用户偏好和约束\n3. 保留未完成的任务\n4. 保持时间顺序\n5. 摘要应能在后续对话中替代原始内容")
|
||||||
|
.bind("请将以下对话压缩为简洁摘要,保留关键信息:\n\n{{messages}}")
|
||||||
|
.bind(&now).execute(pool).await?;
|
||||||
|
|
||||||
|
// extraction 提示词
|
||||||
|
let extraction_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let extraction_ver_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO prompt_templates (id, name, category, description, source, current_version, status, created_at, updated_at)
|
||||||
|
VALUES ($1, 'extraction', 'builtin_extraction', '记忆提取引擎', 'builtin', 1, 'active', $2, $2)"
|
||||||
|
).bind(&extraction_id).bind(&now).execute(pool).await?;
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO prompt_versions (id, template_id, version, system_prompt, user_prompt_template, variables, changelog, min_app_version, created_at)
|
||||||
|
VALUES ($1, $2, 1, $3, $4, '[]', '初始版本', NULL, $5)"
|
||||||
|
).bind(&extraction_ver_id).bind(&extraction_id)
|
||||||
|
.bind("你是一个记忆提取专家。从对话中提取值得长期记住的信息。\n\n提取类型:\n- fact: 用户告知的事实(如\"我的公司叫XXX\")\n- preference: 用户的偏好(如\"我喜欢简洁的回答\")\n- lesson: 本次对话的经验教训\n- task: 未完成的任务或承诺\n\n输出 JSON 数组:\n[\n {\n \"content\": \"记忆内容\",\n \"type\": \"fact/preference/lesson/task\",\n \"importance\": 1-10,\n \"tags\": [\"标签1\", \"标签2\"]\n }\n]")
|
||||||
|
.bind("从以下对话中提取值得长期记住的信息:\n\n{{conversation}}\n\n如果没有值得记忆的内容,返回空数组 []。")
|
||||||
|
.bind(&now).execute(pool).await?;
|
||||||
|
|
||||||
|
tracing::info!("Seeded 3 builtin prompt templates (reflection, compaction, extraction)");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
// PostgreSQL 单元测试需要真实数据库连接,此处保留接口兼容
|
||||||
|
// 集成测试见 tests/integration_test.rs
|
||||||
|
}
|
||||||
129
crates/zclaw-saas/src/error.rs
Normal file
129
crates/zclaw-saas/src/error.rs
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
//! SaaS 错误类型
|
||||||
|
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
/// SaaS 服务错误类型
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum SaasError {
|
||||||
|
#[error("未找到: {0}")]
|
||||||
|
NotFound(String),
|
||||||
|
|
||||||
|
#[error("权限不足: {0}")]
|
||||||
|
Forbidden(String),
|
||||||
|
|
||||||
|
#[error("未认证")]
|
||||||
|
Unauthorized,
|
||||||
|
|
||||||
|
#[error("无效输入: {0}")]
|
||||||
|
InvalidInput(String),
|
||||||
|
|
||||||
|
#[error("认证失败: {0}")]
|
||||||
|
AuthError(String),
|
||||||
|
|
||||||
|
#[error("用户已存在: {0}")]
|
||||||
|
AlreadyExists(String),
|
||||||
|
|
||||||
|
#[error("序列化错误: {0}")]
|
||||||
|
Serialization(#[from] serde_json::Error),
|
||||||
|
|
||||||
|
#[error("IO 错误: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
|
||||||
|
#[error("数据库错误: {0}")]
|
||||||
|
Database(#[from] sqlx::Error),
|
||||||
|
|
||||||
|
#[error("配置错误: {0}")]
|
||||||
|
Config(#[from] toml::de::Error),
|
||||||
|
|
||||||
|
#[error("JWT 错误: {0}")]
|
||||||
|
Jwt(#[from] jsonwebtoken::errors::Error),
|
||||||
|
|
||||||
|
#[error("密码哈希错误: {0}")]
|
||||||
|
PasswordHash(String),
|
||||||
|
|
||||||
|
#[error("TOTP 错误: {0}")]
|
||||||
|
Totp(String),
|
||||||
|
|
||||||
|
#[error("加密错误: {0}")]
|
||||||
|
Encryption(String),
|
||||||
|
|
||||||
|
#[error("中转错误: {0}")]
|
||||||
|
Relay(String),
|
||||||
|
|
||||||
|
#[error("速率限制: {0}")]
|
||||||
|
RateLimited(String),
|
||||||
|
|
||||||
|
#[error("内部错误: {0}")]
|
||||||
|
Internal(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SaasError {
|
||||||
|
/// 获取 HTTP 状态码
|
||||||
|
pub fn status_code(&self) -> StatusCode {
|
||||||
|
match self {
|
||||||
|
Self::NotFound(_) => StatusCode::NOT_FOUND,
|
||||||
|
Self::Forbidden(_) => StatusCode::FORBIDDEN,
|
||||||
|
Self::Unauthorized => StatusCode::UNAUTHORIZED,
|
||||||
|
Self::InvalidInput(_) => StatusCode::BAD_REQUEST,
|
||||||
|
Self::AlreadyExists(_) => StatusCode::CONFLICT,
|
||||||
|
Self::RateLimited(_) => StatusCode::TOO_MANY_REQUESTS,
|
||||||
|
Self::Database(_) | Self::Internal(_) | Self::Io(_) | Self::Serialization(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Self::AuthError(_) => StatusCode::UNAUTHORIZED,
|
||||||
|
Self::Jwt(_) | Self::PasswordHash(_) | Self::Encryption(_) => {
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
}
|
||||||
|
Self::Totp(_) => StatusCode::BAD_REQUEST,
|
||||||
|
Self::Config(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Self::Relay(_) => StatusCode::BAD_GATEWAY,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 获取错误代码
|
||||||
|
pub fn error_code(&self) -> &str {
|
||||||
|
match self {
|
||||||
|
Self::NotFound(_) => "NOT_FOUND",
|
||||||
|
Self::Forbidden(_) => "FORBIDDEN",
|
||||||
|
Self::Unauthorized => "UNAUTHORIZED",
|
||||||
|
Self::InvalidInput(_) => "INVALID_INPUT",
|
||||||
|
Self::AlreadyExists(_) => "ALREADY_EXISTS",
|
||||||
|
Self::RateLimited(_) => "RATE_LIMITED",
|
||||||
|
Self::Database(_) => "DATABASE_ERROR",
|
||||||
|
Self::Io(_) => "IO_ERROR",
|
||||||
|
Self::Serialization(_) => "SERIALIZATION_ERROR",
|
||||||
|
Self::Internal(_) => "INTERNAL_ERROR",
|
||||||
|
Self::AuthError(_) => "AUTH_ERROR",
|
||||||
|
Self::Jwt(_) => "JWT_ERROR",
|
||||||
|
Self::PasswordHash(_) => "PASSWORD_HASH_ERROR",
|
||||||
|
Self::Totp(_) => "TOTP_ERROR",
|
||||||
|
Self::Encryption(_) => "ENCRYPTION_ERROR",
|
||||||
|
Self::Config(_) => "CONFIG_ERROR",
|
||||||
|
Self::Relay(_) => "RELAY_ERROR",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 实现 Axum 响应
|
||||||
|
impl IntoResponse for SaasError {
|
||||||
|
fn into_response(self) -> Response {
|
||||||
|
let status = self.status_code();
|
||||||
|
let (error_code, message) = match &self {
|
||||||
|
// 500 错误不泄露内部细节给客户端
|
||||||
|
Self::Database(_) | Self::Internal(_) | Self::Io(_)
|
||||||
|
| Self::Jwt(_) | Self::Config(_) => {
|
||||||
|
tracing::error!("内部错误 [{}]: {}", self.error_code(), self);
|
||||||
|
(self.error_code().to_string(), "服务内部错误".to_string())
|
||||||
|
}
|
||||||
|
_ => (self.error_code().to_string(), self.to_string()),
|
||||||
|
};
|
||||||
|
let body = json!({
|
||||||
|
"error": error_code,
|
||||||
|
"message": message,
|
||||||
|
});
|
||||||
|
(status, axum::Json(body)).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result 类型别名
|
||||||
|
pub type SaasResult<T> = std::result::Result<T, SaasError>;
|
||||||
25
crates/zclaw-saas/src/lib.rs
Normal file
25
crates/zclaw-saas/src/lib.rs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
//! ZCLAW SaaS Backend
|
||||||
|
//!
|
||||||
|
//! 独立的 SaaS 后端服务,提供账号权限管理、模型配置、请求中转和配置迁移。
|
||||||
|
|
||||||
|
pub mod common;
|
||||||
|
pub mod config;
|
||||||
|
pub mod crypto;
|
||||||
|
pub mod db;
|
||||||
|
pub mod error;
|
||||||
|
pub mod middleware;
|
||||||
|
pub mod models;
|
||||||
|
pub mod scheduler;
|
||||||
|
pub mod state;
|
||||||
|
pub mod tasks;
|
||||||
|
pub mod workers;
|
||||||
|
|
||||||
|
pub mod auth;
|
||||||
|
pub mod account;
|
||||||
|
pub mod model_config;
|
||||||
|
pub mod relay;
|
||||||
|
pub mod migration;
|
||||||
|
pub mod role;
|
||||||
|
pub mod prompt;
|
||||||
|
pub mod agent_template;
|
||||||
|
pub mod telemetry;
|
||||||
164
crates/zclaw-saas/src/main.rs
Normal file
164
crates/zclaw-saas/src/main.rs
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
//! ZCLAW SaaS 服务入口
|
||||||
|
|
||||||
|
use axum::extract::State;
|
||||||
|
use tower_http::timeout::TimeoutLayer;
|
||||||
|
use tracing::info;
|
||||||
|
use zclaw_saas::{config::SaaSConfig, db::init_db, state::AppState};
|
||||||
|
use zclaw_saas::workers::WorkerDispatcher;
|
||||||
|
use zclaw_saas::workers::log_operation::LogOperationWorker;
|
||||||
|
use zclaw_saas::workers::cleanup_refresh_tokens::CleanupRefreshTokensWorker;
|
||||||
|
use zclaw_saas::workers::cleanup_rate_limit::CleanupRateLimitWorker;
|
||||||
|
use zclaw_saas::workers::record_usage::RecordUsageWorker;
|
||||||
|
use zclaw_saas::workers::update_last_used::UpdateLastUsedWorker;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_env_filter(
|
||||||
|
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||||
|
.unwrap_or_else(|_| "zclaw_saas=debug,tower_http=debug".into()),
|
||||||
|
)
|
||||||
|
.init();
|
||||||
|
|
||||||
|
let config = SaaSConfig::load()?;
|
||||||
|
info!("SaaS config loaded: {}:{}", config.server.host, config.server.port);
|
||||||
|
|
||||||
|
let db = init_db(&config.database.url).await?;
|
||||||
|
info!("Database initialized");
|
||||||
|
|
||||||
|
// 初始化 Worker 调度器 + 注册所有 Worker
|
||||||
|
let mut dispatcher = WorkerDispatcher::new(db.clone());
|
||||||
|
dispatcher.register(LogOperationWorker);
|
||||||
|
dispatcher.register(CleanupRefreshTokensWorker);
|
||||||
|
dispatcher.register(CleanupRateLimitWorker);
|
||||||
|
dispatcher.register(RecordUsageWorker);
|
||||||
|
dispatcher.register(UpdateLastUsedWorker);
|
||||||
|
info!("Worker dispatcher initialized (5 workers registered)");
|
||||||
|
|
||||||
|
let state = AppState::new(db.clone(), config.clone(), dispatcher)?;
|
||||||
|
|
||||||
|
// 启动声明式 Scheduler(从 TOML 配置读取定时任务)
|
||||||
|
let scheduler_config = &config.scheduler;
|
||||||
|
zclaw_saas::scheduler::start_scheduler(scheduler_config, db.clone(), state.worker_dispatcher.clone_ref());
|
||||||
|
info!("Scheduler started with {} jobs", scheduler_config.jobs.len());
|
||||||
|
|
||||||
|
// 启动内置 DB 清理任务(设备清理等不通过 Worker 的任务)
|
||||||
|
zclaw_saas::scheduler::start_db_cleanup_tasks(db.clone());
|
||||||
|
|
||||||
|
// 启动内存中的 rate limit 条目清理
|
||||||
|
let rate_limit_state = state.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut interval = tokio::time::interval(std::time::Duration::from_secs(300));
|
||||||
|
loop {
|
||||||
|
interval.tick().await;
|
||||||
|
rate_limit_state.cleanup_rate_limit_entries();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let app = build_router(state).await;
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind(format!("{}:{}", config.server.host, config.server.port))
|
||||||
|
.await?;
|
||||||
|
info!("SaaS server listening on {}:{}", config.server.host, config.server.port);
|
||||||
|
|
||||||
|
axum::serve(listener, app.into_make_service_with_connect_info::<std::net::SocketAddr>()).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn health_handler(State(state): State<AppState>) -> axum::Json<serde_json::Value> {
|
||||||
|
let db_healthy = sqlx::query_scalar::<_, i32>("SELECT 1")
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await
|
||||||
|
.is_ok();
|
||||||
|
|
||||||
|
let status = if db_healthy { "healthy" } else { "degraded" };
|
||||||
|
let _code = if db_healthy { 200 } else { 503 };
|
||||||
|
|
||||||
|
axum::Json(serde_json::json!({
|
||||||
|
"status": status,
|
||||||
|
"database": db_healthy,
|
||||||
|
"timestamp": chrono::Utc::now().to_rfc3339(),
|
||||||
|
"version": env!("CARGO_PKG_VERSION"),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn build_router(state: AppState) -> axum::Router {
|
||||||
|
use axum::middleware;
|
||||||
|
use tower_http::cors::{Any, CorsLayer};
|
||||||
|
use tower_http::trace::TraceLayer;
|
||||||
|
|
||||||
|
use axum::http::HeaderValue;
|
||||||
|
let cors = {
|
||||||
|
let config = state.config.read().await;
|
||||||
|
let is_dev = std::env::var("ZCLAW_SAAS_DEV")
|
||||||
|
.map(|v| v == "true" || v == "1")
|
||||||
|
.unwrap_or(false);
|
||||||
|
if config.server.cors_origins.is_empty() {
|
||||||
|
if is_dev {
|
||||||
|
CorsLayer::new()
|
||||||
|
.allow_origin(Any)
|
||||||
|
.allow_methods(Any)
|
||||||
|
.allow_headers(Any)
|
||||||
|
} else {
|
||||||
|
tracing::error!("生产环境必须配置 server.cors_origins,不能使用 allow_origin(Any)");
|
||||||
|
panic!("生产环境必须配置 server.cors_origins 白名单。开发环境可设置 ZCLAW_SAAS_DEV=true 绕过。");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let origins: Vec<HeaderValue> = config.server.cors_origins.iter()
|
||||||
|
.filter_map(|o: &String| o.parse::<HeaderValue>().ok())
|
||||||
|
.collect();
|
||||||
|
CorsLayer::new()
|
||||||
|
.allow_origin(origins)
|
||||||
|
.allow_methods([
|
||||||
|
axum::http::Method::GET,
|
||||||
|
axum::http::Method::POST,
|
||||||
|
axum::http::Method::PUT,
|
||||||
|
axum::http::Method::PATCH,
|
||||||
|
axum::http::Method::DELETE,
|
||||||
|
axum::http::Method::OPTIONS,
|
||||||
|
])
|
||||||
|
.allow_headers([
|
||||||
|
axum::http::header::AUTHORIZATION,
|
||||||
|
axum::http::header::CONTENT_TYPE,
|
||||||
|
axum::http::HeaderName::from_static("x-request-id"),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let public_routes = zclaw_saas::auth::routes()
|
||||||
|
.route("/api/health", axum::routing::get(health_handler));
|
||||||
|
|
||||||
|
let protected_routes = zclaw_saas::auth::protected_routes()
|
||||||
|
.merge(zclaw_saas::account::routes())
|
||||||
|
.merge(zclaw_saas::model_config::routes())
|
||||||
|
.merge(zclaw_saas::relay::routes())
|
||||||
|
.merge(zclaw_saas::migration::routes())
|
||||||
|
.merge(zclaw_saas::role::routes())
|
||||||
|
.merge(zclaw_saas::prompt::routes())
|
||||||
|
.merge(zclaw_saas::agent_template::routes())
|
||||||
|
.merge(zclaw_saas::telemetry::routes())
|
||||||
|
.layer(middleware::from_fn_with_state(
|
||||||
|
state.clone(),
|
||||||
|
zclaw_saas::middleware::api_version_middleware,
|
||||||
|
))
|
||||||
|
.layer(middleware::from_fn_with_state(
|
||||||
|
state.clone(),
|
||||||
|
zclaw_saas::middleware::request_id_middleware,
|
||||||
|
))
|
||||||
|
.layer(middleware::from_fn_with_state(
|
||||||
|
state.clone(),
|
||||||
|
zclaw_saas::middleware::rate_limit_middleware,
|
||||||
|
))
|
||||||
|
.layer(middleware::from_fn_with_state(
|
||||||
|
state.clone(),
|
||||||
|
zclaw_saas::auth::auth_middleware,
|
||||||
|
));
|
||||||
|
|
||||||
|
axum::Router::new()
|
||||||
|
.merge(public_routes)
|
||||||
|
.merge(protected_routes)
|
||||||
|
.layer(TimeoutLayer::new(std::time::Duration::from_secs(30)))
|
||||||
|
.layer(TraceLayer::new_for_http())
|
||||||
|
.layer(cors)
|
||||||
|
.with_state(state)
|
||||||
|
}
|
||||||
83
crates/zclaw-saas/src/middleware.rs
Normal file
83
crates/zclaw-saas/src/middleware.rs
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
//! 中间件模块
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
body::Body,
|
||||||
|
extract::State,
|
||||||
|
http::{HeaderValue, Request, Response},
|
||||||
|
middleware::Next,
|
||||||
|
response::IntoResponse,
|
||||||
|
};
|
||||||
|
use std::time::Instant;
|
||||||
|
use crate::state::AppState;
|
||||||
|
use crate::error::SaasError;
|
||||||
|
use crate::auth::types::AuthContext;
|
||||||
|
|
||||||
|
/// 请求 ID 追踪中间件
|
||||||
|
/// 为每个请求生成唯一 ID,便于日志追踪
|
||||||
|
pub async fn request_id_middleware(
|
||||||
|
State(_state): State<AppState>,
|
||||||
|
mut req: Request<Body>,
|
||||||
|
next: Next,
|
||||||
|
) -> Response<Body> {
|
||||||
|
let request_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
|
||||||
|
req.extensions_mut().insert(request_id.clone());
|
||||||
|
|
||||||
|
let mut response = next.run(req).await;
|
||||||
|
|
||||||
|
if let Ok(value) = HeaderValue::from_str(&request_id) {
|
||||||
|
response.headers_mut().insert("X-Request-ID", value);
|
||||||
|
}
|
||||||
|
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
/// API 版本控制中间件
|
||||||
|
/// 在响应头中添加版本信息
|
||||||
|
pub async fn api_version_middleware(
|
||||||
|
State(_state): State<AppState>,
|
||||||
|
req: Request<Body>,
|
||||||
|
next: Next,
|
||||||
|
) -> Response<Body> {
|
||||||
|
let mut response = next.run(req).await;
|
||||||
|
|
||||||
|
response.headers_mut().insert("X-API-Version", HeaderValue::from_static("1.0.0"));
|
||||||
|
response.headers_mut().insert("X-API-Deprecated", HeaderValue::from_static("false"));
|
||||||
|
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 速率限制中间件
|
||||||
|
/// 基于账号的请求频率限制
|
||||||
|
pub async fn rate_limit_middleware(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
req: Request<Body>,
|
||||||
|
next: Next,
|
||||||
|
) -> Response<Body> {
|
||||||
|
let account_id = req.extensions()
|
||||||
|
.get::<AuthContext>()
|
||||||
|
.map(|ctx| ctx.account_id.clone())
|
||||||
|
.unwrap_or_else(|| "anonymous".to_string());
|
||||||
|
|
||||||
|
// 无锁读取 rate limit 配置(避免每个请求获取 RwLock)
|
||||||
|
let rate_limit = state.rate_limit_rpm() as usize;
|
||||||
|
|
||||||
|
let key = format!("rate_limit:{}", account_id);
|
||||||
|
|
||||||
|
let now = Instant::now();
|
||||||
|
let window_start = now - std::time::Duration::from_secs(60);
|
||||||
|
|
||||||
|
let mut entries = state.rate_limit_entries.entry(key).or_insert_with(Vec::new);
|
||||||
|
entries.retain(|&time| time > window_start);
|
||||||
|
|
||||||
|
if entries.len() >= rate_limit {
|
||||||
|
return SaasError::RateLimited(format!(
|
||||||
|
"请求频率超限,每分钟最多 {} 次请求",
|
||||||
|
rate_limit
|
||||||
|
)).into_response();
|
||||||
|
}
|
||||||
|
|
||||||
|
entries.push(now);
|
||||||
|
|
||||||
|
next.run(req).await
|
||||||
|
}
|
||||||
181
crates/zclaw-saas/src/migration/handlers.rs
Normal file
181
crates/zclaw-saas/src/migration/handlers.rs
Normal file
@@ -0,0 +1,181 @@
|
|||||||
|
//! 配置迁移 HTTP 处理器
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
extract::{Extension, Path, Query, State},
|
||||||
|
http::StatusCode, Json,
|
||||||
|
};
|
||||||
|
use crate::state::AppState;
|
||||||
|
use crate::error::SaasResult;
|
||||||
|
use crate::auth::types::AuthContext;
|
||||||
|
use crate::auth::handlers::{check_permission, log_operation};
|
||||||
|
use crate::common::PaginatedResponse;
|
||||||
|
use super::{types::*, service};
|
||||||
|
|
||||||
|
/// GET /api/v1/config/items?category=xxx&source=xxx&page=1&page_size=20
|
||||||
|
pub async fn list_config_items(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Query(query): Query<ConfigQuery>,
|
||||||
|
_ctx: Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<PaginatedResponse<ConfigItemInfo>>> {
|
||||||
|
let filter_query = ConfigQuery {
|
||||||
|
category: query.category.clone(),
|
||||||
|
source: query.source.clone(),
|
||||||
|
page: None,
|
||||||
|
page_size: None,
|
||||||
|
};
|
||||||
|
service::list_config_items(&state.db, &filter_query, query.page, query.page_size).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/config/items/:id
|
||||||
|
pub async fn get_config_item(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
_ctx: Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<ConfigItemInfo>> {
|
||||||
|
service::get_config_item(&state.db, &id).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/config/items (admin only)
|
||||||
|
pub async fn create_config_item(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<CreateConfigItemRequest>,
|
||||||
|
) -> SaasResult<(StatusCode, Json<ConfigItemInfo>)> {
|
||||||
|
check_permission(&ctx, "config:write")?;
|
||||||
|
let item = service::create_config_item(&state.db, &req).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "config.create", "config_item", &item.id, None, ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok((StatusCode::CREATED, Json(item)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// PATCH /api/v1/config/items/:id (admin only)
|
||||||
|
pub async fn update_config_item(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<UpdateConfigItemRequest>,
|
||||||
|
) -> SaasResult<Json<ConfigItemInfo>> {
|
||||||
|
check_permission(&ctx, "config:write")?;
|
||||||
|
let item = service::update_config_item(&state.db, &id, &req).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "config.update", "config_item", &id, None, ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(item))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// DELETE /api/v1/config/items/:id (admin only)
|
||||||
|
pub async fn delete_config_item(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
check_permission(&ctx, "config:write")?;
|
||||||
|
service::delete_config_item(&state.db, &id).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "config.delete", "config_item", &id, None, ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(serde_json::json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/config/analysis
|
||||||
|
pub async fn analyze_config(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
_ctx: Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<ConfigAnalysis>> {
|
||||||
|
service::analyze_config(&state.db).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/config/seed (admin only)
|
||||||
|
pub async fn seed_config(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
check_permission(&ctx, "config:write")?;
|
||||||
|
let count = service::seed_default_config_items(&state.db).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "config.seed", "config_item", "batch", Some(serde_json::json!({"count": count})), ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(serde_json::json!({"created": count})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/config/sync (需要 config:write 权限)
|
||||||
|
pub async fn sync_config(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<SyncConfigRequest>,
|
||||||
|
) -> SaasResult<Json<super::service::ConfigSyncResult>> {
|
||||||
|
// 权限检查:仅 config:write 可推送配置
|
||||||
|
check_permission(&ctx, "config:write")?;
|
||||||
|
|
||||||
|
let result = super::service::sync_config(&state.db, &ctx.account_id, &req).await?;
|
||||||
|
|
||||||
|
// 审计日志
|
||||||
|
log_operation(
|
||||||
|
&state.db,
|
||||||
|
&ctx.account_id,
|
||||||
|
"config.sync",
|
||||||
|
"config",
|
||||||
|
"batch",
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"client_fingerprint": req.client_fingerprint,
|
||||||
|
"action": req.action,
|
||||||
|
"config_count": req.config_keys.len(),
|
||||||
|
})),
|
||||||
|
ctx.client_ip.as_deref(),
|
||||||
|
).await.ok();
|
||||||
|
|
||||||
|
Ok(Json(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/config/diff
|
||||||
|
/// 计算客户端与 SaaS 端的配置差异 (不修改数据)
|
||||||
|
pub async fn config_diff(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(_ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<SyncConfigRequest>,
|
||||||
|
) -> SaasResult<Json<ConfigDiffResponse>> {
|
||||||
|
// diff 操作虽然不修改数据,但涉及敏感配置信息,仍需认证用户
|
||||||
|
service::compute_config_diff(&state.db, &req).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/config/sync-logs?page=1&page_size=20
|
||||||
|
pub async fn list_sync_logs(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Query(params): Query<std::collections::HashMap<String, String>>,
|
||||||
|
) -> SaasResult<Json<crate::common::PaginatedResponse<ConfigSyncLogInfo>>> {
|
||||||
|
let page: u32 = params.get("page").and_then(|v| v.parse().ok()).unwrap_or(1).max(1);
|
||||||
|
let page_size: u32 = params.get("page_size").and_then(|v| v.parse().ok()).unwrap_or(20).min(100);
|
||||||
|
service::list_sync_logs(&state.db, &ctx.account_id, page, page_size).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/config/pull?since=2026-03-28T00:00:00Z
|
||||||
|
/// 批量拉取配置(供桌面端启动时一次性拉取)
|
||||||
|
/// 返回扁平的 key-value map,可选 since 参数过滤仅返回该时间之后更新的配置
|
||||||
|
pub async fn pull_config(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
_ctx: Extension<AuthContext>,
|
||||||
|
Query(params): Query<std::collections::HashMap<String, String>>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
let since = params.get("since").cloned();
|
||||||
|
let items = service::fetch_all_config_items(
|
||||||
|
&state.db,
|
||||||
|
&ConfigQuery { category: None, source: None, page: None, page_size: None },
|
||||||
|
).await?;
|
||||||
|
|
||||||
|
let mut configs: Vec<serde_json::Value> = Vec::new();
|
||||||
|
for item in items {
|
||||||
|
// 如果指定了 since,只返回 updated_at > since 的配置
|
||||||
|
if let Some(ref since_val) = since {
|
||||||
|
if item.updated_at <= *since_val {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
configs.push(serde_json::json!({
|
||||||
|
"key": item.key_path,
|
||||||
|
"category": item.category,
|
||||||
|
"value": item.current_value,
|
||||||
|
"value_type": item.value_type,
|
||||||
|
"default": item.default_value,
|
||||||
|
"updated_at": item.updated_at,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Json(serde_json::json!({
|
||||||
|
"configs": configs,
|
||||||
|
"pulled_at": chrono::Utc::now().to_rfc3339(),
|
||||||
|
})))
|
||||||
|
}
|
||||||
21
crates/zclaw-saas/src/migration/mod.rs
Normal file
21
crates/zclaw-saas/src/migration/mod.rs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
//! 配置迁移模块
|
||||||
|
|
||||||
|
pub mod types;
|
||||||
|
pub mod service;
|
||||||
|
pub mod handlers;
|
||||||
|
|
||||||
|
use axum::routing::{get, post};
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
/// 配置迁移路由 (需要认证)
|
||||||
|
pub fn routes() -> axum::Router<AppState> {
|
||||||
|
axum::Router::new()
|
||||||
|
.route("/api/v1/config/items", get(handlers::list_config_items).post(handlers::create_config_item))
|
||||||
|
.route("/api/v1/config/items/:id", get(handlers::get_config_item).put(handlers::update_config_item).delete(handlers::delete_config_item))
|
||||||
|
.route("/api/v1/config/analysis", get(handlers::analyze_config))
|
||||||
|
.route("/api/v1/config/seed", post(handlers::seed_config))
|
||||||
|
.route("/api/v1/config/sync", post(handlers::sync_config))
|
||||||
|
.route("/api/v1/config/diff", post(handlers::config_diff))
|
||||||
|
.route("/api/v1/config/sync-logs", get(handlers::list_sync_logs))
|
||||||
|
.route("/api/v1/config/pull", get(handlers::pull_config))
|
||||||
|
}
|
||||||
470
crates/zclaw-saas/src/migration/service.rs
Normal file
470
crates/zclaw-saas/src/migration/service.rs
Normal file
@@ -0,0 +1,470 @@
|
|||||||
|
//! 配置迁移业务逻辑
|
||||||
|
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use crate::error::{SaasError, SaasResult};
|
||||||
|
use crate::common::{PaginatedResponse, normalize_pagination};
|
||||||
|
use crate::models::{ConfigItemRow, ConfigSyncLogRow};
|
||||||
|
use super::types::*;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
// ============ Config Items ============
|
||||||
|
|
||||||
|
/// Fetch all config items matching the query (internal use, no pagination).
|
||||||
|
pub(crate) async fn fetch_all_config_items(
|
||||||
|
db: &PgPool, query: &ConfigQuery,
|
||||||
|
) -> SaasResult<Vec<ConfigItemInfo>> {
|
||||||
|
let sql = match (&query.category, &query.source) {
|
||||||
|
(Some(_), Some(_)) => {
|
||||||
|
"SELECT id, category, key_path, value_type, current_value, default_value, source, description, requires_restart, created_at, updated_at
|
||||||
|
FROM config_items WHERE category = $1 AND source = $2 ORDER BY category, key_path"
|
||||||
|
}
|
||||||
|
(Some(_), None) => {
|
||||||
|
"SELECT id, category, key_path, value_type, current_value, default_value, source, description, requires_restart, created_at, updated_at
|
||||||
|
FROM config_items WHERE category = $1 ORDER BY key_path"
|
||||||
|
}
|
||||||
|
(None, Some(_)) => {
|
||||||
|
"SELECT id, category, key_path, value_type, current_value, default_value, source, description, requires_restart, created_at, updated_at
|
||||||
|
FROM config_items WHERE source = $1 ORDER BY category, key_path"
|
||||||
|
}
|
||||||
|
(None, None) => {
|
||||||
|
"SELECT id, category, key_path, value_type, current_value, default_value, source, description, requires_restart, created_at, updated_at
|
||||||
|
FROM config_items ORDER BY category, key_path"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut query_builder = sqlx::query_as::<_, ConfigItemRow>(sql);
|
||||||
|
|
||||||
|
if let Some(cat) = &query.category {
|
||||||
|
query_builder = query_builder.bind(cat);
|
||||||
|
}
|
||||||
|
if let Some(src) = &query.source {
|
||||||
|
query_builder = query_builder.bind(src);
|
||||||
|
}
|
||||||
|
|
||||||
|
let rows = query_builder.fetch_all(db).await?;
|
||||||
|
Ok(rows.into_iter().map(|r| {
|
||||||
|
ConfigItemInfo { id: r.id, category: r.category, key_path: r.key_path, value_type: r.value_type, current_value: r.current_value, default_value: r.default_value, source: r.source, description: r.description, requires_restart: r.requires_restart, created_at: r.created_at, updated_at: r.updated_at }
|
||||||
|
}).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Paginated list of config items (HTTP handler entry point).
|
||||||
|
pub async fn list_config_items(
|
||||||
|
db: &PgPool, query: &ConfigQuery,
|
||||||
|
page: Option<u32>, page_size: Option<u32>,
|
||||||
|
) -> SaasResult<PaginatedResponse<ConfigItemInfo>> {
|
||||||
|
let (p, ps, offset) = normalize_pagination(page, page_size);
|
||||||
|
|
||||||
|
// Build WHERE clause for count and data queries
|
||||||
|
let (where_clause, has_category, has_source) = match (&query.category, &query.source) {
|
||||||
|
(Some(_), Some(_)) => ("WHERE category = $1 AND source = $2", true, true),
|
||||||
|
(Some(_), None) => ("WHERE category = $1", true, false),
|
||||||
|
(None, Some(_)) => ("WHERE source = $1", false, true),
|
||||||
|
(None, None) => ("", false, false),
|
||||||
|
};
|
||||||
|
|
||||||
|
let count_sql = format!("SELECT COUNT(*) FROM config_items {}", where_clause);
|
||||||
|
let data_sql = format!(
|
||||||
|
"SELECT id, category, key_path, value_type, current_value, default_value, source, description, requires_restart, created_at, updated_at
|
||||||
|
FROM config_items {} ORDER BY category, key_path LIMIT {} OFFSET {}",
|
||||||
|
where_clause, "$p", "$o"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Determine param indices for LIMIT/OFFSET based on filter params
|
||||||
|
let (limit_idx, offset_idx) = match (has_category, has_source) {
|
||||||
|
(true, true) => ("$3", "$4"),
|
||||||
|
(true, false) | (false, true) => ("$2", "$3"),
|
||||||
|
(false, false) => ("$1", "$2"),
|
||||||
|
};
|
||||||
|
let data_sql = data_sql.replace("$p", limit_idx).replace("$o", offset_idx);
|
||||||
|
|
||||||
|
let mut count_query = sqlx::query_scalar::<_, i64>(&count_sql);
|
||||||
|
if has_category { count_query = count_query.bind(&query.category); }
|
||||||
|
if has_source { count_query = count_query.bind(&query.source); }
|
||||||
|
let total: i64 = count_query.fetch_one(db).await?;
|
||||||
|
|
||||||
|
let mut data_query = sqlx::query_as::<_, ConfigItemRow>(&data_sql);
|
||||||
|
if has_category { data_query = data_query.bind(&query.category); }
|
||||||
|
if has_source { data_query = data_query.bind(&query.source); }
|
||||||
|
let rows = data_query.bind(ps as i64).bind(offset).fetch_all(db).await?;
|
||||||
|
|
||||||
|
let items = rows.into_iter().map(|r| {
|
||||||
|
ConfigItemInfo { id: r.id, category: r.category, key_path: r.key_path, value_type: r.value_type, current_value: r.current_value, default_value: r.default_value, source: r.source, description: r.description, requires_restart: r.requires_restart, created_at: r.created_at, updated_at: r.updated_at }
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
Ok(PaginatedResponse { items, total, page: p, page_size: ps })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_config_item(db: &PgPool, item_id: &str) -> SaasResult<ConfigItemInfo> {
|
||||||
|
let row: Option<ConfigItemRow> =
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, category, key_path, value_type, current_value, default_value, source, description, requires_restart, created_at, updated_at
|
||||||
|
FROM config_items WHERE id = $1"
|
||||||
|
)
|
||||||
|
.bind(item_id)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let r = row.ok_or_else(|| SaasError::NotFound(format!("配置项 {} 不存在", item_id)))?;
|
||||||
|
|
||||||
|
Ok(ConfigItemInfo { id: r.id, category: r.category, key_path: r.key_path, value_type: r.value_type, current_value: r.current_value, default_value: r.default_value, source: r.source, description: r.description, requires_restart: r.requires_restart, created_at: r.created_at, updated_at: r.updated_at })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_config_item(
|
||||||
|
db: &PgPool, req: &CreateConfigItemRequest,
|
||||||
|
) -> SaasResult<ConfigItemInfo> {
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let source = req.source.as_deref().unwrap_or("local");
|
||||||
|
let requires_restart = req.requires_restart.unwrap_or(false);
|
||||||
|
|
||||||
|
// 检查唯一性
|
||||||
|
let existing: Option<(String,)> = sqlx::query_as(
|
||||||
|
"SELECT id FROM config_items WHERE category = $1 AND key_path = $2"
|
||||||
|
)
|
||||||
|
.bind(&req.category).bind(&req.key_path)
|
||||||
|
.fetch_optional(db).await?;
|
||||||
|
|
||||||
|
if existing.is_some() {
|
||||||
|
return Err(SaasError::AlreadyExists(format!(
|
||||||
|
"配置项 {}:{} 已存在", req.category, req.key_path
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO config_items (id, category, key_path, value_type, current_value, default_value, source, description, requires_restart, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10)"
|
||||||
|
)
|
||||||
|
.bind(&id).bind(&req.category).bind(&req.key_path).bind(&req.value_type)
|
||||||
|
.bind(&req.current_value).bind(&req.default_value).bind(source)
|
||||||
|
.bind(&req.description).bind(requires_restart).bind(&now)
|
||||||
|
.execute(db).await?;
|
||||||
|
|
||||||
|
get_config_item(db, &id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_config_item(
|
||||||
|
db: &PgPool, item_id: &str, req: &UpdateConfigItemRequest,
|
||||||
|
) -> SaasResult<ConfigItemInfo> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let mut updates = Vec::new();
|
||||||
|
let mut params: Vec<String> = Vec::new();
|
||||||
|
let mut param_idx = 1usize;
|
||||||
|
|
||||||
|
if let Some(ref v) = req.current_value { updates.push(format!("current_value = ${}", param_idx)); params.push(v.clone()); param_idx += 1; }
|
||||||
|
if let Some(ref v) = req.source { updates.push(format!("source = ${}", param_idx)); params.push(v.clone()); param_idx += 1; }
|
||||||
|
if let Some(ref v) = req.description { updates.push(format!("description = ${}", param_idx)); params.push(v.clone()); param_idx += 1; }
|
||||||
|
|
||||||
|
if updates.is_empty() {
|
||||||
|
return get_config_item(db, item_id).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
updates.push(format!("updated_at = ${}", param_idx));
|
||||||
|
params.push(now);
|
||||||
|
param_idx += 1;
|
||||||
|
params.push(item_id.to_string());
|
||||||
|
|
||||||
|
let sql = format!("UPDATE config_items SET {} WHERE id = ${}", updates.join(", "), param_idx);
|
||||||
|
let mut query = sqlx::query(&sql);
|
||||||
|
for p in ¶ms {
|
||||||
|
query = query.bind(p);
|
||||||
|
}
|
||||||
|
query.execute(db).await?;
|
||||||
|
|
||||||
|
get_config_item(db, item_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_config_item(db: &PgPool, item_id: &str) -> SaasResult<()> {
|
||||||
|
let result = sqlx::query("DELETE FROM config_items WHERE id = $1")
|
||||||
|
.bind(item_id).execute(db).await?;
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
return Err(SaasError::NotFound(format!("配置项 {} 不存在", item_id)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Config Analysis ============
|
||||||
|
|
||||||
|
pub async fn analyze_config(db: &PgPool) -> SaasResult<ConfigAnalysis> {
|
||||||
|
let items = fetch_all_config_items(db, &ConfigQuery { category: None, source: None, page: None, page_size: None }).await?;
|
||||||
|
|
||||||
|
let mut categories: std::collections::HashMap<String, (i64, i64)> = std::collections::HashMap::new();
|
||||||
|
for item in &items {
|
||||||
|
let entry = categories.entry(item.category.clone()).or_insert((0, 0));
|
||||||
|
entry.0 += 1;
|
||||||
|
if item.source == "saas" {
|
||||||
|
entry.1 += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let category_summaries: Vec<CategorySummary> = categories.into_iter()
|
||||||
|
.map(|(category, (count, saas_managed))| CategorySummary { category, count, saas_managed })
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(ConfigAnalysis {
|
||||||
|
total_items: items.len() as i64,
|
||||||
|
categories: category_summaries,
|
||||||
|
items,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 种子默认配置项
|
||||||
|
pub async fn seed_default_config_items(db: &PgPool) -> SaasResult<usize> {
|
||||||
|
let defaults = [
|
||||||
|
("server", "server.host", "string", Some("127.0.0.1"), Some("127.0.0.1"), "服务器监听地址"),
|
||||||
|
("server", "server.port", "integer", Some("4200"), Some("4200"), "服务器端口"),
|
||||||
|
("server", "server.cors_origins", "array", None, None, "CORS 允许的源"),
|
||||||
|
("agent", "agent.defaults.default_model", "string", Some("zhipu/glm-4-plus"), Some("zhipu/glm-4-plus"), "默认模型"),
|
||||||
|
("agent", "agent.defaults.fallback_models", "array", None, None, "回退模型列表"),
|
||||||
|
("agent", "agent.defaults.max_sessions", "integer", Some("10"), Some("10"), "最大并发会话数"),
|
||||||
|
("agent", "agent.defaults.heartbeat_interval", "duration", Some("1h"), Some("1h"), "心跳间隔"),
|
||||||
|
("agent", "agent.defaults.session_timeout", "duration", Some("24h"), Some("24h"), "会话超时"),
|
||||||
|
("memory", "agent.defaults.memory.max_history_length", "integer", Some("100"), Some("100"), "最大历史长度"),
|
||||||
|
("memory", "agent.defaults.memory.summarize_threshold", "integer", Some("50"), Some("50"), "摘要阈值"),
|
||||||
|
("llm", "llm.default_provider", "string", Some("zhipu"), Some("zhipu"), "默认 LLM Provider"),
|
||||||
|
("llm", "llm.temperature", "float", Some("0.7"), Some("0.7"), "默认温度"),
|
||||||
|
("llm", "llm.max_tokens", "integer", Some("4096"), Some("4096"), "默认最大 token 数"),
|
||||||
|
// 安全策略配置
|
||||||
|
("security", "security.autonomy_level", "string", Some("standard"), Some("standard"), "自主级别: minimal/standard/full"),
|
||||||
|
("security", "security.max_tokens_per_request", "integer", Some("32768"), Some("32768"), "单次请求最大 Token 数"),
|
||||||
|
("security", "security.shell_enabled", "boolean", Some("true"), Some("true"), "是否启用 Shell 工具"),
|
||||||
|
("security", "security.shell_whitelist", "array", Some("[]"), Some("[]"), "Shell 命令白名单 (空=全部禁止)"),
|
||||||
|
("security", "security.file_write_enabled", "boolean", Some("true"), Some("true"), "是否允许文件写入"),
|
||||||
|
("security", "security.network_access_enabled", "boolean", Some("true"), Some("true"), "是否允许网络访问"),
|
||||||
|
("security", "security.browser_enabled", "boolean", Some("true"), Some("true"), "是否启用浏览器自动化"),
|
||||||
|
("security", "security.max_concurrent_tasks", "integer", Some("3"), Some("3"), "最大并发自主任务数"),
|
||||||
|
("security", "security.approval_required", "boolean", Some("false"), Some("false"), "高风险操作是否需要审批"),
|
||||||
|
("security", "security.content_filter_enabled", "boolean", Some("true"), Some("true"), "是否启用内容过滤"),
|
||||||
|
("security", "security.audit_log_enabled", "boolean", Some("true"), Some("true"), "是否启用审计日志"),
|
||||||
|
("security", "security.audit_log_max_entries", "integer", Some("500"), Some("500"), "审计日志最大条目数"),
|
||||||
|
];
|
||||||
|
|
||||||
|
let mut created = 0;
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
for (category, key_path, value_type, default_value, current_value, description) in defaults {
|
||||||
|
let existing: Option<(String,)> = sqlx::query_as(
|
||||||
|
"SELECT id FROM config_items WHERE category = $1 AND key_path = $2"
|
||||||
|
)
|
||||||
|
.bind(category).bind(key_path)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if existing.is_none() {
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO config_items (id, category, key_path, value_type, current_value, default_value, source, description, requires_restart, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, 'local', $7, false, $8, $8)"
|
||||||
|
)
|
||||||
|
.bind(&id).bind(category).bind(key_path).bind(value_type)
|
||||||
|
.bind(current_value).bind(default_value).bind(description).bind(&now)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
created += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(created)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Config Sync ============
|
||||||
|
|
||||||
|
/// 计算客户端与 SaaS 端的配置差异
|
||||||
|
pub async fn compute_config_diff(
|
||||||
|
db: &PgPool, req: &SyncConfigRequest,
|
||||||
|
) -> SaasResult<ConfigDiffResponse> {
|
||||||
|
let saas_items = fetch_all_config_items(db, &ConfigQuery { category: None, source: None, page: None, page_size: None }).await?;
|
||||||
|
|
||||||
|
let mut items = Vec::new();
|
||||||
|
let mut conflicts = 0usize;
|
||||||
|
|
||||||
|
for key in &req.config_keys {
|
||||||
|
let client_val = req.client_values.get(key)
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.map(|s| s.to_string());
|
||||||
|
|
||||||
|
// 查找 SaaS 端的值
|
||||||
|
let saas_item = saas_items.iter().find(|item| item.key_path == *key);
|
||||||
|
let saas_val = saas_item.and_then(|item| item.current_value.clone());
|
||||||
|
|
||||||
|
let conflict = match (&client_val, &saas_val) {
|
||||||
|
(Some(a), Some(b)) => a != b,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
|
||||||
|
if conflict {
|
||||||
|
conflicts += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
items.push(ConfigDiffItem {
|
||||||
|
key_path: key.clone(),
|
||||||
|
client_value: client_val,
|
||||||
|
saas_value: saas_val,
|
||||||
|
conflict,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ConfigDiffResponse {
|
||||||
|
total_keys: items.len(),
|
||||||
|
conflicts,
|
||||||
|
items,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 执行配置同步 (实际写入 config_items)
|
||||||
|
pub async fn sync_config(
|
||||||
|
db: &PgPool, account_id: &str, req: &SyncConfigRequest,
|
||||||
|
) -> SaasResult<ConfigSyncResult> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let config_keys_str = serde_json::to_string(&req.config_keys)?;
|
||||||
|
let client_values_str = Some(serde_json::to_string(&req.client_values)?);
|
||||||
|
|
||||||
|
// 获取 SaaS 端的配置值
|
||||||
|
let saas_items = fetch_all_config_items(db, &ConfigQuery { category: None, source: None, page: None, page_size: None }).await?;
|
||||||
|
let mut updated = 0i64;
|
||||||
|
let mut created = 0i64;
|
||||||
|
let mut skipped = 0i64;
|
||||||
|
let mut conflicts: Vec<String> = Vec::new();
|
||||||
|
|
||||||
|
for key in &req.config_keys {
|
||||||
|
let client_val = req.client_values.get(key)
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.map(|s| s.to_string());
|
||||||
|
|
||||||
|
let saas_item = saas_items.iter().find(|item| item.key_path == *key);
|
||||||
|
|
||||||
|
match req.action.as_str() {
|
||||||
|
"push" => {
|
||||||
|
// 客户端推送 → 覆盖 SaaS 值 (带 CAS 保护)
|
||||||
|
if let Some(val) = &client_val {
|
||||||
|
if let Some(item) = saas_item {
|
||||||
|
// CAS: 如果客户端提供了该 key 的 timestamp,做乐观锁
|
||||||
|
if let Some(ref client_ts) = req.client_timestamps.get(key) {
|
||||||
|
let result = sqlx::query(
|
||||||
|
"UPDATE config_items SET current_value = $1, source = 'local', updated_at = $2 WHERE id = $3 AND updated_at = $4"
|
||||||
|
)
|
||||||
|
.bind(val).bind(&now).bind(&item.id).bind(client_ts)
|
||||||
|
.execute(db).await?;
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
// SaaS 端已被修改 → 跳过,记录冲突
|
||||||
|
tracing::warn!(
|
||||||
|
"[ConfigSync] CAS conflict for key '{}': client_ts={}, saas_ts={}",
|
||||||
|
key, client_ts, item.updated_at
|
||||||
|
);
|
||||||
|
conflicts.push(key.clone());
|
||||||
|
skipped += 1;
|
||||||
|
} else {
|
||||||
|
updated += 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 无 CAS timestamp → 无条件覆盖 (向后兼容)
|
||||||
|
sqlx::query("UPDATE config_items SET current_value = $1, source = 'local', updated_at = $2 WHERE id = $3")
|
||||||
|
.bind(val).bind(&now).bind(&item.id)
|
||||||
|
.execute(db).await?;
|
||||||
|
updated += 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 推送时 SaaS 不存在该 key → 创建新配置项
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let parts: Vec<&str> = key.splitn(2, '.').collect();
|
||||||
|
let category = parts.first().unwrap_or(&"general").to_string();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO config_items (id, category, key_path, value_type, current_value, default_value, source, description, requires_restart, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, 'string', $4, $4, 'local', '客户端推送', false, $5, $5)"
|
||||||
|
)
|
||||||
|
.bind(&id).bind(&category).bind(key).bind(val).bind(&now)
|
||||||
|
.execute(db).await?;
|
||||||
|
created += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"merge" => {
|
||||||
|
// 合并: 客户端有值且 SaaS 无值 → 填入; 都有值 → SaaS 优先保留
|
||||||
|
if let Some(val) = &client_val {
|
||||||
|
if let Some(item) = saas_item {
|
||||||
|
if item.current_value.is_none() || item.current_value.as_deref() == Some("") {
|
||||||
|
sqlx::query("UPDATE config_items SET current_value = $1, source = 'local', updated_at = $2 WHERE id = $3")
|
||||||
|
.bind(val).bind(&now).bind(&item.id)
|
||||||
|
.execute(db).await?;
|
||||||
|
updated += 1;
|
||||||
|
} else {
|
||||||
|
// 冲突: SaaS 有值 → 保留 SaaS 值
|
||||||
|
skipped += 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 客户端有但 SaaS 完全没有的 key → 不自动创建 (需要管理员先创建)
|
||||||
|
skipped += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
// 默认: 记录日志但不修改 (向后兼容旧行为)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录同步日志
|
||||||
|
let saas_values: serde_json::Value = saas_items.iter()
|
||||||
|
.filter(|item| req.config_keys.contains(&item.key_path))
|
||||||
|
.map(|item| {
|
||||||
|
serde_json::json!({
|
||||||
|
"value": item.current_value,
|
||||||
|
"source": item.source,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let saas_values_str = Some(serde_json::to_string(&saas_values)?);
|
||||||
|
let resolution = req.action.clone();
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO config_sync_log (account_id, client_fingerprint, action, config_keys, client_values, saas_values, resolution, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"
|
||||||
|
)
|
||||||
|
.bind(account_id).bind(&req.client_fingerprint)
|
||||||
|
.bind(&req.action).bind(&config_keys_str).bind(&client_values_str)
|
||||||
|
.bind(&saas_values_str).bind(&resolution).bind(&now)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(ConfigSyncResult { updated, created, skipped, conflicts })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 同步结果
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct ConfigSyncResult {
|
||||||
|
pub updated: i64,
|
||||||
|
pub created: i64,
|
||||||
|
pub skipped: i64,
|
||||||
|
/// Keys skipped due to CAS conflict (SaaS was modified after client read)
|
||||||
|
pub conflicts: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_sync_logs(
|
||||||
|
db: &PgPool, account_id: &str, page: u32, page_size: u32,
|
||||||
|
) -> SaasResult<crate::common::PaginatedResponse<ConfigSyncLogInfo>> {
|
||||||
|
let offset = ((page - 1) * page_size) as i64;
|
||||||
|
|
||||||
|
let total: (i64,) = sqlx::query_as(
|
||||||
|
"SELECT COUNT(*) FROM config_sync_log WHERE account_id = $1"
|
||||||
|
)
|
||||||
|
.bind(account_id)
|
||||||
|
.fetch_one(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let rows: Vec<ConfigSyncLogRow> =
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, account_id, client_fingerprint, action, config_keys, client_values, saas_values, resolution, created_at
|
||||||
|
FROM config_sync_log WHERE account_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3"
|
||||||
|
)
|
||||||
|
.bind(account_id)
|
||||||
|
.bind(page_size as i64)
|
||||||
|
.bind(offset)
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let items = rows.into_iter().map(|r| {
|
||||||
|
ConfigSyncLogInfo { id: r.id, account_id: r.account_id, client_fingerprint: r.client_fingerprint, action: r.action, config_keys: r.config_keys, client_values: r.client_values, saas_values: r.saas_values, resolution: r.resolution, created_at: r.created_at }
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
Ok(crate::common::PaginatedResponse { items, total: total.0, page, page_size })
|
||||||
|
}
|
||||||
113
crates/zclaw-saas/src/migration/types.rs
Normal file
113
crates/zclaw-saas/src/migration/types.rs
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
//! 配置迁移类型定义
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// 配置项信息
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ConfigItemInfo {
|
||||||
|
pub id: String,
|
||||||
|
pub category: String,
|
||||||
|
pub key_path: String,
|
||||||
|
pub value_type: String,
|
||||||
|
pub current_value: Option<String>,
|
||||||
|
pub default_value: Option<String>,
|
||||||
|
pub source: String,
|
||||||
|
pub description: Option<String>,
|
||||||
|
pub requires_restart: bool,
|
||||||
|
pub created_at: String,
|
||||||
|
pub updated_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建配置项请求
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct CreateConfigItemRequest {
|
||||||
|
pub category: String,
|
||||||
|
pub key_path: String,
|
||||||
|
pub value_type: String,
|
||||||
|
pub current_value: Option<String>,
|
||||||
|
pub default_value: Option<String>,
|
||||||
|
pub source: Option<String>,
|
||||||
|
pub description: Option<String>,
|
||||||
|
pub requires_restart: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 更新配置项请求
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct UpdateConfigItemRequest {
|
||||||
|
pub current_value: Option<String>,
|
||||||
|
pub source: Option<String>,
|
||||||
|
pub description: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 配置同步日志
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct ConfigSyncLogInfo {
|
||||||
|
pub id: i64,
|
||||||
|
pub account_id: String,
|
||||||
|
pub client_fingerprint: String,
|
||||||
|
pub action: String,
|
||||||
|
pub config_keys: String,
|
||||||
|
pub client_values: Option<String>,
|
||||||
|
pub saas_values: Option<String>,
|
||||||
|
pub resolution: Option<String>,
|
||||||
|
pub created_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 配置分析结果
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct ConfigAnalysis {
|
||||||
|
pub total_items: i64,
|
||||||
|
pub categories: Vec<CategorySummary>,
|
||||||
|
pub items: Vec<ConfigItemInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct CategorySummary {
|
||||||
|
pub category: String,
|
||||||
|
pub count: i64,
|
||||||
|
pub saas_managed: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 配置同步请求
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct SyncConfigRequest {
|
||||||
|
pub client_fingerprint: String,
|
||||||
|
/// 同步方向: "push", "pull", "merge"
|
||||||
|
#[serde(default = "default_sync_action")]
|
||||||
|
pub action: String,
|
||||||
|
pub config_keys: Vec<String>,
|
||||||
|
pub client_values: serde_json::Value,
|
||||||
|
/// Client-side timestamps per key for optimistic locking (push CAS).
|
||||||
|
/// Maps `key_path` → `updated_at` as seen by client before this push.
|
||||||
|
/// Keys present here get `WHERE updated_at = $ts` on UPDATE; absent keys use unconditional overwrite.
|
||||||
|
#[serde(default)]
|
||||||
|
pub client_timestamps: std::collections::HashMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_sync_action() -> String { "push".to_string() }
|
||||||
|
|
||||||
|
/// 配置差异项
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct ConfigDiffItem {
|
||||||
|
pub key_path: String,
|
||||||
|
pub client_value: Option<String>,
|
||||||
|
pub saas_value: Option<String>,
|
||||||
|
pub conflict: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 配置差异响应
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct ConfigDiffResponse {
|
||||||
|
pub items: Vec<ConfigDiffItem>,
|
||||||
|
pub total_keys: usize,
|
||||||
|
pub conflicts: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 配置查询参数
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct ConfigQuery {
|
||||||
|
pub category: Option<String>,
|
||||||
|
pub source: Option<String>,
|
||||||
|
pub page: Option<u32>,
|
||||||
|
pub page_size: Option<u32>,
|
||||||
|
}
|
||||||
219
crates/zclaw-saas/src/model_config/handlers.rs
Normal file
219
crates/zclaw-saas/src/model_config/handlers.rs
Normal file
@@ -0,0 +1,219 @@
|
|||||||
|
//! 模型配置 HTTP 处理器
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
extract::{Extension, Path, Query, State},
|
||||||
|
http::StatusCode, Json,
|
||||||
|
};
|
||||||
|
use crate::state::AppState;
|
||||||
|
use crate::error::{SaasResult, SaasError};
|
||||||
|
use crate::auth::types::AuthContext;
|
||||||
|
use crate::auth::handlers::{log_operation, check_permission};
|
||||||
|
use crate::common::PaginatedResponse;
|
||||||
|
use super::{types::*, service};
|
||||||
|
|
||||||
|
// ============ Providers ============
|
||||||
|
|
||||||
|
/// GET /api/v1/providers?enabled=true&page=1&page_size=20
|
||||||
|
pub async fn list_providers(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
_ctx: Extension<AuthContext>,
|
||||||
|
Query(params): Query<std::collections::HashMap<String, String>>,
|
||||||
|
) -> SaasResult<Json<PaginatedResponse<ProviderInfo>>> {
|
||||||
|
let page = params.get("page").and_then(|v| v.parse().ok());
|
||||||
|
let page_size = params.get("page_size").and_then(|v| v.parse().ok());
|
||||||
|
let enabled_filter = params.get("enabled").and_then(|v| v.parse().ok());
|
||||||
|
service::list_providers(&state.db, page, page_size, enabled_filter).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/providers/:id
|
||||||
|
pub async fn get_provider(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
_ctx: Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<ProviderInfo>> {
|
||||||
|
service::get_provider(&state.db, &id).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/providers (admin only)
|
||||||
|
pub async fn create_provider(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<CreateProviderRequest>,
|
||||||
|
) -> SaasResult<(StatusCode, Json<ProviderInfo>)> {
|
||||||
|
check_permission(&ctx, "provider:manage")?;
|
||||||
|
let config = state.config.read().await;
|
||||||
|
let enc_key = config.api_key_encryption_key()
|
||||||
|
.map_err(|e| SaasError::Internal(e.to_string()))?;
|
||||||
|
drop(config);
|
||||||
|
let provider = service::create_provider(&state.db, &req, &enc_key).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "provider.create", "provider", &provider.id,
|
||||||
|
Some(serde_json::json!({"name": &req.name})), ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok((StatusCode::CREATED, Json(provider)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// PATCH /api/v1/providers/:id (admin only)
|
||||||
|
pub async fn update_provider(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<UpdateProviderRequest>,
|
||||||
|
) -> SaasResult<Json<ProviderInfo>> {
|
||||||
|
check_permission(&ctx, "provider:manage")?;
|
||||||
|
let config = state.config.read().await;
|
||||||
|
let enc_key = config.api_key_encryption_key()
|
||||||
|
.map_err(|e| SaasError::Internal(e.to_string()))?;
|
||||||
|
drop(config);
|
||||||
|
let provider = service::update_provider(&state.db, &id, &req, &enc_key).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "provider.update", "provider", &id, None, ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(provider))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// DELETE /api/v1/providers/:id (admin only)
|
||||||
|
pub async fn delete_provider(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
check_permission(&ctx, "provider:manage")?;
|
||||||
|
service::delete_provider(&state.db, &id).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "provider.delete", "provider", &id, None, ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(serde_json::json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Models ============
|
||||||
|
|
||||||
|
/// GET /api/v1/models?provider_id=xxx&page=1&page_size=20
|
||||||
|
pub async fn list_models(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Query(params): Query<std::collections::HashMap<String, String>>,
|
||||||
|
_ctx: Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<PaginatedResponse<ModelInfo>>> {
|
||||||
|
let provider_id = params.get("provider_id").map(|s| s.as_str());
|
||||||
|
let page = params.get("page").and_then(|v| v.parse().ok());
|
||||||
|
let page_size = params.get("page_size").and_then(|v| v.parse().ok());
|
||||||
|
service::list_models(&state.db, provider_id, page, page_size).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/models/:id
|
||||||
|
pub async fn get_model(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
_ctx: Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<ModelInfo>> {
|
||||||
|
service::get_model(&state.db, &id).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/models (admin only)
|
||||||
|
pub async fn create_model(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<CreateModelRequest>,
|
||||||
|
) -> SaasResult<(StatusCode, Json<ModelInfo>)> {
|
||||||
|
check_permission(&ctx, "model:manage")?;
|
||||||
|
let model = service::create_model(&state.db, &req).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "model.create", "model", &model.id,
|
||||||
|
Some(serde_json::json!({"model_id": &req.model_id, "provider_id": &req.provider_id})), ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok((StatusCode::CREATED, Json(model)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// PATCH /api/v1/models/:id (admin only)
|
||||||
|
pub async fn update_model(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<UpdateModelRequest>,
|
||||||
|
) -> SaasResult<Json<ModelInfo>> {
|
||||||
|
check_permission(&ctx, "model:manage")?;
|
||||||
|
let model = service::update_model(&state.db, &id, &req).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "model.update", "model", &id, None, ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(model))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// DELETE /api/v1/models/:id (admin only)
|
||||||
|
pub async fn delete_model(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
check_permission(&ctx, "model:manage")?;
|
||||||
|
service::delete_model(&state.db, &id).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "model.delete", "model", &id, None, ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(serde_json::json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Account API Keys ============
|
||||||
|
|
||||||
|
/// GET /api/v1/keys?provider_id=xxx&page=1&page_size=20
|
||||||
|
pub async fn list_api_keys(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Query(params): Query<std::collections::HashMap<String, String>>,
|
||||||
|
) -> SaasResult<Json<PaginatedResponse<AccountApiKeyInfo>>> {
|
||||||
|
let provider_id = params.get("provider_id").map(|s| s.as_str());
|
||||||
|
let page = params.get("page").and_then(|v| v.parse().ok());
|
||||||
|
let page_size = params.get("page_size").and_then(|v| v.parse().ok());
|
||||||
|
service::list_account_api_keys(&state.db, &ctx.account_id, provider_id, page, page_size).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/keys
|
||||||
|
pub async fn create_api_key(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<CreateAccountApiKeyRequest>,
|
||||||
|
) -> SaasResult<(StatusCode, Json<AccountApiKeyInfo>)> {
|
||||||
|
let config = state.config.read().await;
|
||||||
|
let enc_key = config.api_key_encryption_key()
|
||||||
|
.map_err(|e| SaasError::Internal(e.to_string()))?;
|
||||||
|
drop(config);
|
||||||
|
let key = service::create_account_api_key(&state.db, &ctx.account_id, &req, &enc_key).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "api_key.create", "api_key", &key.id,
|
||||||
|
Some(serde_json::json!({"provider_id": &req.provider_id})), ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok((StatusCode::CREATED, Json(key)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /api/v1/keys/:id/rotate
|
||||||
|
pub async fn rotate_api_key(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Json(req): Json<RotateApiKeyRequest>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
let config = state.config.read().await;
|
||||||
|
let enc_key = config.api_key_encryption_key()
|
||||||
|
.map_err(|e| SaasError::Internal(e.to_string()))?;
|
||||||
|
drop(config);
|
||||||
|
service::rotate_account_api_key(&state.db, &id, &ctx.account_id, &req.new_key_value, &enc_key).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "api_key.rotate", "api_key", &id, None, ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(serde_json::json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// DELETE /api/v1/keys/:id
|
||||||
|
pub async fn revoke_api_key(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<serde_json::Value>> {
|
||||||
|
service::revoke_account_api_key(&state.db, &id, &ctx.account_id).await?;
|
||||||
|
log_operation(&state.db, &ctx.account_id, "api_key.revoke", "api_key", &id, None, ctx.client_ip.as_deref()).await?;
|
||||||
|
Ok(Json(serde_json::json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Usage ============
|
||||||
|
|
||||||
|
/// GET /api/v1/usage?from=...&to=...&provider_id=...&model_id=...
|
||||||
|
pub async fn get_usage(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ctx): Extension<AuthContext>,
|
||||||
|
Query(params): Query<UsageQuery>,
|
||||||
|
) -> SaasResult<Json<UsageStats>> {
|
||||||
|
service::get_usage_stats(&state.db, &ctx.account_id, ¶ms).await.map(Json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/providers/:id/models (便捷路由)
|
||||||
|
pub async fn list_provider_models(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(provider_id): Path<String>,
|
||||||
|
_ctx: Extension<AuthContext>,
|
||||||
|
) -> SaasResult<Json<PaginatedResponse<ModelInfo>>> {
|
||||||
|
service::list_models(&state.db, Some(&provider_id), None, None).await.map(Json)
|
||||||
|
}
|
||||||
26
crates/zclaw-saas/src/model_config/mod.rs
Normal file
26
crates/zclaw-saas/src/model_config/mod.rs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
//! 模型配置模块
|
||||||
|
|
||||||
|
pub mod types;
|
||||||
|
pub mod service;
|
||||||
|
pub mod handlers;
|
||||||
|
|
||||||
|
use axum::routing::{delete, get, post};
|
||||||
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
/// 模型配置路由 (需要认证)
|
||||||
|
pub fn routes() -> axum::Router<AppState> {
|
||||||
|
axum::Router::new()
|
||||||
|
// Providers
|
||||||
|
.route("/api/v1/providers", get(handlers::list_providers).post(handlers::create_provider))
|
||||||
|
.route("/api/v1/providers/:id", get(handlers::get_provider).patch(handlers::update_provider).delete(handlers::delete_provider))
|
||||||
|
.route("/api/v1/providers/:id/models", get(handlers::list_provider_models))
|
||||||
|
// Models
|
||||||
|
.route("/api/v1/models", get(handlers::list_models).post(handlers::create_model))
|
||||||
|
.route("/api/v1/models/:id", get(handlers::get_model).patch(handlers::update_model).delete(handlers::delete_model))
|
||||||
|
// Account API Keys
|
||||||
|
.route("/api/v1/keys", get(handlers::list_api_keys).post(handlers::create_api_key))
|
||||||
|
.route("/api/v1/keys/:id", delete(handlers::revoke_api_key))
|
||||||
|
.route("/api/v1/keys/:id/rotate", post(handlers::rotate_api_key))
|
||||||
|
// Usage
|
||||||
|
.route("/api/v1/usage", get(handlers::get_usage))
|
||||||
|
}
|
||||||
517
crates/zclaw-saas/src/model_config/service.rs
Normal file
517
crates/zclaw-saas/src/model_config/service.rs
Normal file
@@ -0,0 +1,517 @@
|
|||||||
|
//! 模型配置业务逻辑
|
||||||
|
|
||||||
|
use sqlx::{PgPool, Row};
|
||||||
|
use crate::error::{SaasError, SaasResult};
|
||||||
|
use crate::common::{PaginatedResponse, normalize_pagination};
|
||||||
|
use crate::crypto;
|
||||||
|
use crate::models::{ProviderRow, ModelRow, AccountApiKeyRow, UsageByModelRow, UsageByDayRow};
|
||||||
|
use super::types::*;
|
||||||
|
|
||||||
|
// ============ Providers ============
|
||||||
|
|
||||||
|
pub async fn list_providers(
|
||||||
|
db: &PgPool, page: Option<u32>, page_size: Option<u32>, enabled_filter: Option<bool>,
|
||||||
|
) -> SaasResult<PaginatedResponse<ProviderInfo>> {
|
||||||
|
let (p, ps, offset) = normalize_pagination(page, page_size);
|
||||||
|
|
||||||
|
let (count_sql, data_sql) = if enabled_filter.is_some() {
|
||||||
|
(
|
||||||
|
"SELECT COUNT(*) FROM providers WHERE enabled = $1",
|
||||||
|
"SELECT id, name, display_name, base_url, api_protocol, enabled, rate_limit_rpm, rate_limit_tpm, created_at, updated_at
|
||||||
|
FROM providers WHERE enabled = $1 ORDER BY name LIMIT $2 OFFSET $3",
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(
|
||||||
|
"SELECT COUNT(*) FROM providers",
|
||||||
|
"SELECT id, name, display_name, base_url, api_protocol, enabled, rate_limit_rpm, rate_limit_tpm, created_at, updated_at
|
||||||
|
FROM providers ORDER BY name LIMIT $1 OFFSET $2",
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let total: (i64,) = if let Some(en) = enabled_filter {
|
||||||
|
sqlx::query_as(count_sql).bind(en).fetch_one(db).await?
|
||||||
|
} else {
|
||||||
|
sqlx::query_as(count_sql).fetch_one(db).await?
|
||||||
|
};
|
||||||
|
|
||||||
|
let rows: Vec<ProviderRow> =
|
||||||
|
if let Some(en) = enabled_filter {
|
||||||
|
sqlx::query_as(data_sql)
|
||||||
|
.bind(en).bind(ps as i64).bind(offset)
|
||||||
|
.fetch_all(db).await?
|
||||||
|
} else {
|
||||||
|
sqlx::query_as(data_sql)
|
||||||
|
.bind(ps as i64).bind(offset)
|
||||||
|
.fetch_all(db).await?
|
||||||
|
};
|
||||||
|
|
||||||
|
let items = rows.into_iter().map(|r| {
|
||||||
|
ProviderInfo { id: r.id, name: r.name, display_name: r.display_name, base_url: r.base_url, api_protocol: r.api_protocol, enabled: r.enabled, rate_limit_rpm: r.rate_limit_rpm, rate_limit_tpm: r.rate_limit_tpm, created_at: r.created_at, updated_at: r.updated_at }
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
Ok(PaginatedResponse { items, total: total.0, page: p, page_size: ps })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_provider(db: &PgPool, provider_id: &str) -> SaasResult<ProviderInfo> {
|
||||||
|
let row: Option<ProviderRow> =
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, name, display_name, base_url, api_protocol, enabled, rate_limit_rpm, rate_limit_tpm, created_at, updated_at
|
||||||
|
FROM providers WHERE id = $1"
|
||||||
|
)
|
||||||
|
.bind(provider_id)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let r = row.ok_or_else(|| SaasError::NotFound(format!("Provider {} 不存在", provider_id)))?;
|
||||||
|
|
||||||
|
Ok(ProviderInfo { id: r.id, name: r.name, display_name: r.display_name, base_url: r.base_url, api_protocol: r.api_protocol, enabled: r.enabled, rate_limit_rpm: r.rate_limit_rpm, rate_limit_tpm: r.rate_limit_tpm, created_at: r.created_at, updated_at: r.updated_at })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_provider(db: &PgPool, req: &CreateProviderRequest, enc_key: &[u8; 32]) -> SaasResult<ProviderInfo> {
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
// 检查名称唯一性
|
||||||
|
let existing: Option<(String,)> = sqlx::query_as("SELECT id FROM providers WHERE name = $1")
|
||||||
|
.bind(&req.name).fetch_optional(db).await?;
|
||||||
|
if existing.is_some() {
|
||||||
|
return Err(SaasError::AlreadyExists(format!("Provider '{}' 已存在", req.name)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 加密 API Key 后存储
|
||||||
|
let encrypted_api_key = if let Some(ref key) = req.api_key {
|
||||||
|
if key.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
crypto::encrypt_value(key, enc_key)?
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO providers (id, name, display_name, api_key, base_url, api_protocol, enabled, rate_limit_rpm, rate_limit_tpm, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, true, $7, $8, $9, $9)"
|
||||||
|
)
|
||||||
|
.bind(&id).bind(&req.name).bind(&req.display_name).bind(&encrypted_api_key)
|
||||||
|
.bind(&req.base_url).bind(&req.api_protocol).bind(&req.rate_limit_rpm).bind(&req.rate_limit_tpm).bind(&now)
|
||||||
|
.execute(db).await?;
|
||||||
|
|
||||||
|
get_provider(db, &id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_provider(
|
||||||
|
db: &PgPool, provider_id: &str, req: &UpdateProviderRequest, enc_key: &[u8; 32],
|
||||||
|
) -> SaasResult<ProviderInfo> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let mut updates = Vec::new();
|
||||||
|
let mut params: Vec<Box<dyn std::fmt::Display + Send + Sync>> = Vec::new();
|
||||||
|
let mut param_idx = 1;
|
||||||
|
|
||||||
|
if let Some(ref v) = req.display_name { updates.push(format!("display_name = ${}", param_idx)); params.push(Box::new(v.clone())); param_idx += 1; }
|
||||||
|
if let Some(ref v) = req.base_url { updates.push(format!("base_url = ${}", param_idx)); params.push(Box::new(v.clone())); param_idx += 1; }
|
||||||
|
if let Some(ref v) = req.api_protocol { updates.push(format!("api_protocol = ${}", param_idx)); params.push(Box::new(v.clone())); param_idx += 1; }
|
||||||
|
if let Some(ref v) = req.api_key {
|
||||||
|
let encrypted = if v.is_empty() { String::new() } else { crypto::encrypt_value(v, enc_key)? };
|
||||||
|
updates.push(format!("api_key = ${}", param_idx)); params.push(Box::new(encrypted)); param_idx += 1;
|
||||||
|
}
|
||||||
|
if let Some(v) = req.enabled { updates.push(format!("enabled = ${}", param_idx)); params.push(Box::new(v)); param_idx += 1; }
|
||||||
|
if let Some(v) = req.rate_limit_rpm { updates.push(format!("rate_limit_rpm = ${}", param_idx)); params.push(Box::new(v)); param_idx += 1; }
|
||||||
|
if let Some(v) = req.rate_limit_tpm { updates.push(format!("rate_limit_tpm = ${}", param_idx)); params.push(Box::new(v)); param_idx += 1; }
|
||||||
|
|
||||||
|
if updates.is_empty() {
|
||||||
|
return get_provider(db, provider_id).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
updates.push(format!("updated_at = ${}", param_idx));
|
||||||
|
params.push(Box::new(now.clone()));
|
||||||
|
param_idx += 1;
|
||||||
|
params.push(Box::new(provider_id.to_string()));
|
||||||
|
|
||||||
|
let sql = format!("UPDATE providers SET {} WHERE id = ${}", updates.join(", "), param_idx);
|
||||||
|
let mut query = sqlx::query(&sql);
|
||||||
|
for p in ¶ms {
|
||||||
|
query = query.bind(format!("{}", p));
|
||||||
|
}
|
||||||
|
query.execute(db).await?;
|
||||||
|
|
||||||
|
get_provider(db, provider_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_provider(db: &PgPool, provider_id: &str) -> SaasResult<()> {
|
||||||
|
let result = sqlx::query("DELETE FROM providers WHERE id = $1")
|
||||||
|
.bind(provider_id).execute(db).await?;
|
||||||
|
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
return Err(SaasError::NotFound(format!("Provider {} 不存在", provider_id)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Models ============
|
||||||
|
|
||||||
|
pub async fn list_models(
|
||||||
|
db: &PgPool, provider_id: Option<&str>, page: Option<u32>, page_size: Option<u32>,
|
||||||
|
) -> SaasResult<PaginatedResponse<ModelInfo>> {
|
||||||
|
let (p, ps, offset) = normalize_pagination(page, page_size);
|
||||||
|
|
||||||
|
let (count_sql, data_sql) = if provider_id.is_some() {
|
||||||
|
(
|
||||||
|
"SELECT COUNT(*) FROM models WHERE provider_id = $1",
|
||||||
|
"SELECT id, provider_id, model_id, alias, context_window, max_output_tokens, supports_streaming, supports_vision, enabled, pricing_input, pricing_output, created_at, updated_at
|
||||||
|
FROM models WHERE provider_id = $1 ORDER BY alias LIMIT $2 OFFSET $3",
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(
|
||||||
|
"SELECT COUNT(*) FROM models",
|
||||||
|
"SELECT id, provider_id, model_id, alias, context_window, max_output_tokens, supports_streaming, supports_vision, enabled, pricing_input, pricing_output, created_at, updated_at
|
||||||
|
FROM models ORDER BY provider_id, alias LIMIT $1 OFFSET $2",
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let total: (i64,) = if let Some(pid) = provider_id {
|
||||||
|
sqlx::query_as(count_sql).bind(pid).fetch_one(db).await?
|
||||||
|
} else {
|
||||||
|
sqlx::query_as(count_sql).fetch_one(db).await?
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut query = sqlx::query_as::<_, ModelRow>(data_sql);
|
||||||
|
if let Some(pid) = provider_id {
|
||||||
|
query = query.bind(pid);
|
||||||
|
}
|
||||||
|
let rows = query.bind(ps as i64).bind(offset).fetch_all(db).await?;
|
||||||
|
|
||||||
|
let items = rows.into_iter().map(|r| {
|
||||||
|
ModelInfo { id: r.id, provider_id: r.provider_id, model_id: r.model_id, alias: r.alias, context_window: r.context_window, max_output_tokens: r.max_output_tokens, supports_streaming: r.supports_streaming, supports_vision: r.supports_vision, enabled: r.enabled, pricing_input: r.pricing_input, pricing_output: r.pricing_output, created_at: r.created_at, updated_at: r.updated_at }
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
Ok(PaginatedResponse { items, total: total.0, page: p, page_size: ps })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_model(db: &PgPool, req: &CreateModelRequest) -> SaasResult<ModelInfo> {
|
||||||
|
// 验证 provider 存在
|
||||||
|
let provider = get_provider(db, &req.provider_id).await?;
|
||||||
|
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
// 检查 model 唯一性
|
||||||
|
let existing: Option<(String,)> = sqlx::query_as(
|
||||||
|
"SELECT id FROM models WHERE provider_id = $1 AND model_id = $2"
|
||||||
|
)
|
||||||
|
.bind(&req.provider_id).bind(&req.model_id)
|
||||||
|
.fetch_optional(db).await?;
|
||||||
|
|
||||||
|
if existing.is_some() {
|
||||||
|
return Err(SaasError::AlreadyExists(format!(
|
||||||
|
"模型 '{}' 已存在于 provider '{}'", req.model_id, provider.name
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let ctx = req.context_window.unwrap_or(8192);
|
||||||
|
let max_out = req.max_output_tokens.unwrap_or(4096);
|
||||||
|
let streaming = req.supports_streaming.unwrap_or(true);
|
||||||
|
let vision = req.supports_vision.unwrap_or(false);
|
||||||
|
let pi = req.pricing_input.unwrap_or(0.0);
|
||||||
|
let po = req.pricing_output.unwrap_or(0.0);
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO models (id, provider_id, model_id, alias, context_window, max_output_tokens, supports_streaming, supports_vision, enabled, pricing_input, pricing_output, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, true, $9, $10, $11, $11)"
|
||||||
|
)
|
||||||
|
.bind(&id).bind(&req.provider_id).bind(&req.model_id).bind(&req.alias)
|
||||||
|
.bind(ctx).bind(max_out).bind(streaming).bind(vision).bind(pi).bind(po).bind(&now)
|
||||||
|
.execute(db).await?;
|
||||||
|
|
||||||
|
get_model(db, &id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_model(db: &PgPool, model_id: &str) -> SaasResult<ModelInfo> {
|
||||||
|
let row: Option<ModelRow> =
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, provider_id, model_id, alias, context_window, max_output_tokens, supports_streaming, supports_vision, enabled, pricing_input, pricing_output, created_at, updated_at
|
||||||
|
FROM models WHERE id = $1"
|
||||||
|
)
|
||||||
|
.bind(model_id)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let r = row.ok_or_else(|| SaasError::NotFound(format!("模型 {} 不存在", model_id)))?;
|
||||||
|
|
||||||
|
Ok(ModelInfo { id: r.id, provider_id: r.provider_id, model_id: r.model_id, alias: r.alias, context_window: r.context_window, max_output_tokens: r.max_output_tokens, supports_streaming: r.supports_streaming, supports_vision: r.supports_vision, enabled: r.enabled, pricing_input: r.pricing_input, pricing_output: r.pricing_output, created_at: r.created_at, updated_at: r.updated_at })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_model(
|
||||||
|
db: &PgPool, model_id: &str, req: &UpdateModelRequest,
|
||||||
|
) -> SaasResult<ModelInfo> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let mut updates = Vec::new();
|
||||||
|
let mut params: Vec<Box<dyn std::fmt::Display + Send + Sync>> = Vec::new();
|
||||||
|
let mut param_idx = 1;
|
||||||
|
|
||||||
|
if let Some(ref v) = req.alias { updates.push(format!("alias = ${}", param_idx)); params.push(Box::new(v.clone())); param_idx += 1; }
|
||||||
|
if let Some(v) = req.context_window { updates.push(format!("context_window = ${}", param_idx)); params.push(Box::new(v)); param_idx += 1; }
|
||||||
|
if let Some(v) = req.max_output_tokens { updates.push(format!("max_output_tokens = ${}", param_idx)); params.push(Box::new(v)); param_idx += 1; }
|
||||||
|
if let Some(v) = req.supports_streaming { updates.push(format!("supports_streaming = ${}", param_idx)); params.push(Box::new(v)); param_idx += 1; }
|
||||||
|
if let Some(v) = req.supports_vision { updates.push(format!("supports_vision = ${}", param_idx)); params.push(Box::new(v)); param_idx += 1; }
|
||||||
|
if let Some(v) = req.enabled { updates.push(format!("enabled = ${}", param_idx)); params.push(Box::new(v)); param_idx += 1; }
|
||||||
|
if let Some(v) = req.pricing_input { updates.push(format!("pricing_input = ${}", param_idx)); params.push(Box::new(v)); param_idx += 1; }
|
||||||
|
if let Some(v) = req.pricing_output { updates.push(format!("pricing_output = ${}", param_idx)); params.push(Box::new(v)); param_idx += 1; }
|
||||||
|
|
||||||
|
if updates.is_empty() {
|
||||||
|
return get_model(db, model_id).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
updates.push(format!("updated_at = ${}", param_idx));
|
||||||
|
params.push(Box::new(now.clone()));
|
||||||
|
param_idx += 1;
|
||||||
|
params.push(Box::new(model_id.to_string()));
|
||||||
|
|
||||||
|
let sql = format!("UPDATE models SET {} WHERE id = ${}", updates.join(", "), param_idx);
|
||||||
|
let mut query = sqlx::query(&sql);
|
||||||
|
for p in ¶ms {
|
||||||
|
query = query.bind(format!("{}", p));
|
||||||
|
}
|
||||||
|
query.execute(db).await?;
|
||||||
|
|
||||||
|
get_model(db, model_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_model(db: &PgPool, model_id: &str) -> SaasResult<()> {
|
||||||
|
let result = sqlx::query("DELETE FROM models WHERE id = $1")
|
||||||
|
.bind(model_id).execute(db).await?;
|
||||||
|
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
return Err(SaasError::NotFound(format!("模型 {} 不存在", model_id)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Account API Keys ============
|
||||||
|
|
||||||
|
pub async fn list_account_api_keys(
|
||||||
|
db: &PgPool, account_id: &str, provider_id: Option<&str>,
|
||||||
|
page: Option<u32>, page_size: Option<u32>,
|
||||||
|
) -> SaasResult<PaginatedResponse<AccountApiKeyInfo>> {
|
||||||
|
let (p, ps, offset) = normalize_pagination(page, page_size);
|
||||||
|
|
||||||
|
// Build COUNT and data queries based on whether provider_id is provided
|
||||||
|
let (count_sql, data_sql) = if provider_id.is_some() {
|
||||||
|
(
|
||||||
|
"SELECT COUNT(*) FROM account_api_keys WHERE account_id = $1 AND provider_id = $2 AND revoked_at IS NULL",
|
||||||
|
"SELECT id, provider_id, key_label, permissions, enabled, last_used_at, created_at, key_value
|
||||||
|
FROM account_api_keys WHERE account_id = $1 AND provider_id = $2 AND revoked_at IS NULL ORDER BY created_at DESC LIMIT $3 OFFSET $4",
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(
|
||||||
|
"SELECT COUNT(*) FROM account_api_keys WHERE account_id = $1 AND revoked_at IS NULL",
|
||||||
|
"SELECT id, provider_id, key_label, permissions, enabled, last_used_at, created_at, key_value
|
||||||
|
FROM account_api_keys WHERE account_id = $1 AND revoked_at IS NULL ORDER BY created_at DESC LIMIT $2 OFFSET $3",
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let total: (i64,) = if provider_id.is_some() {
|
||||||
|
let mut q = sqlx::query_as(count_sql).bind(account_id);
|
||||||
|
if let Some(pid) = provider_id { q = q.bind(pid); }
|
||||||
|
q.fetch_one(db).await?
|
||||||
|
} else {
|
||||||
|
sqlx::query_as(count_sql).bind(account_id).fetch_one(db).await?
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut query = sqlx::query_as::<_, AccountApiKeyRow>(data_sql)
|
||||||
|
.bind(account_id);
|
||||||
|
if let Some(pid) = provider_id {
|
||||||
|
query = query.bind(pid);
|
||||||
|
}
|
||||||
|
let rows = query.bind(ps as i64).bind(offset).fetch_all(db).await?;
|
||||||
|
|
||||||
|
let items = rows.into_iter().map(|r| {
|
||||||
|
let permissions: Vec<String> = serde_json::from_str(&r.permissions).unwrap_or_default();
|
||||||
|
let masked = mask_api_key(&r.key_value);
|
||||||
|
AccountApiKeyInfo { id: r.id, provider_id: r.provider_id, key_label: r.key_label, permissions, enabled: r.enabled, last_used_at: r.last_used_at, created_at: r.created_at, masked_key: masked }
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
Ok(PaginatedResponse { items, total: total.0, page: p, page_size: ps })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_account_api_key(
|
||||||
|
db: &PgPool, account_id: &str, req: &CreateAccountApiKeyRequest, enc_key: &[u8; 32],
|
||||||
|
) -> SaasResult<AccountApiKeyInfo> {
|
||||||
|
// 验证 provider 存在
|
||||||
|
get_provider(db, &req.provider_id).await?;
|
||||||
|
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let permissions = serde_json::to_string(&req.permissions)?;
|
||||||
|
|
||||||
|
// 加密 key_value 后存储
|
||||||
|
let encrypted_key_value = crypto::encrypt_value(&req.key_value, enc_key)?;
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO account_api_keys (id, account_id, provider_id, key_value, key_label, permissions, enabled, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, true, $7, $7)"
|
||||||
|
)
|
||||||
|
.bind(&id).bind(account_id).bind(&req.provider_id).bind(&encrypted_key_value)
|
||||||
|
.bind(&req.key_label).bind(&permissions).bind(&now)
|
||||||
|
.execute(db).await?;
|
||||||
|
|
||||||
|
let masked = mask_api_key(&req.key_value);
|
||||||
|
Ok(AccountApiKeyInfo {
|
||||||
|
id, provider_id: req.provider_id.clone(), key_label: req.key_label.clone(),
|
||||||
|
permissions: req.permissions.clone(), enabled: true, last_used_at: None,
|
||||||
|
created_at: now, masked_key: masked,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn rotate_account_api_key(
|
||||||
|
db: &PgPool, key_id: &str, account_id: &str, new_key_value: &str, enc_key: &[u8; 32],
|
||||||
|
) -> SaasResult<()> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let encrypted_value = crypto::encrypt_value(new_key_value, enc_key)?;
|
||||||
|
let result = sqlx::query(
|
||||||
|
"UPDATE account_api_keys SET key_value = $1, updated_at = $2 WHERE id = $3 AND account_id = $4 AND revoked_at IS NULL"
|
||||||
|
)
|
||||||
|
.bind(&encrypted_value).bind(&now).bind(key_id).bind(account_id)
|
||||||
|
.execute(db).await?;
|
||||||
|
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
return Err(SaasError::NotFound("API Key 不存在或已撤销".into()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn revoke_account_api_key(
|
||||||
|
db: &PgPool, key_id: &str, account_id: &str,
|
||||||
|
) -> SaasResult<()> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let result = sqlx::query(
|
||||||
|
"UPDATE account_api_keys SET revoked_at = $1 WHERE id = $2 AND account_id = $3 AND revoked_at IS NULL"
|
||||||
|
)
|
||||||
|
.bind(&now).bind(key_id).bind(account_id)
|
||||||
|
.execute(db).await?;
|
||||||
|
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
return Err(SaasError::NotFound("API Key 不存在或已撤销".into()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Usage Statistics ============
|
||||||
|
|
||||||
|
pub async fn get_usage_stats(
|
||||||
|
db: &PgPool, account_id: &str, query: &UsageQuery,
|
||||||
|
) -> SaasResult<UsageStats> {
|
||||||
|
let mut param_idx = 1;
|
||||||
|
let mut where_clauses = vec![format!("account_id = ${}", param_idx)];
|
||||||
|
let mut params: Vec<String> = vec![account_id.to_string()];
|
||||||
|
param_idx += 1;
|
||||||
|
|
||||||
|
if let Some(ref from) = query.from {
|
||||||
|
where_clauses.push(format!("created_at >= ${}", param_idx));
|
||||||
|
params.push(from.clone());
|
||||||
|
param_idx += 1;
|
||||||
|
}
|
||||||
|
if let Some(ref to) = query.to {
|
||||||
|
where_clauses.push(format!("created_at <= ${}", param_idx));
|
||||||
|
params.push(to.clone());
|
||||||
|
param_idx += 1;
|
||||||
|
}
|
||||||
|
if let Some(ref pid) = query.provider_id {
|
||||||
|
where_clauses.push(format!("provider_id = ${}", param_idx));
|
||||||
|
params.push(pid.clone());
|
||||||
|
param_idx += 1;
|
||||||
|
}
|
||||||
|
if let Some(ref mid) = query.model_id {
|
||||||
|
where_clauses.push(format!("model_id = ${}", param_idx));
|
||||||
|
params.push(mid.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
let where_sql = where_clauses.join(" AND ");
|
||||||
|
|
||||||
|
// 总量统计
|
||||||
|
let total_sql = format!(
|
||||||
|
"SELECT COUNT(*)::bigint, COALESCE(SUM(input_tokens), 0), COALESCE(SUM(output_tokens), 0)
|
||||||
|
FROM usage_records WHERE {}", where_sql
|
||||||
|
);
|
||||||
|
let mut total_query = sqlx::query(&total_sql);
|
||||||
|
for p in ¶ms {
|
||||||
|
total_query = total_query.bind(p);
|
||||||
|
}
|
||||||
|
let row = total_query.fetch_one(db).await?;
|
||||||
|
let total_requests: i64 = row.try_get(0).unwrap_or(0);
|
||||||
|
let total_input: i64 = row.try_get(1).unwrap_or(0);
|
||||||
|
let total_output: i64 = row.try_get(2).unwrap_or(0);
|
||||||
|
|
||||||
|
// 按模型统计
|
||||||
|
let by_model_sql = format!(
|
||||||
|
"SELECT provider_id, model_id, COUNT(*)::bigint AS request_count, COALESCE(SUM(input_tokens), 0) AS input_tokens, COALESCE(SUM(output_tokens), 0) AS output_tokens
|
||||||
|
FROM usage_records WHERE {} GROUP BY provider_id, model_id ORDER BY COUNT(*) DESC LIMIT 20",
|
||||||
|
where_sql
|
||||||
|
);
|
||||||
|
let mut by_model_query = sqlx::query_as::<_, UsageByModelRow>(&by_model_sql);
|
||||||
|
for p in ¶ms {
|
||||||
|
by_model_query = by_model_query.bind(p);
|
||||||
|
}
|
||||||
|
let by_model_rows = by_model_query.fetch_all(db).await?;
|
||||||
|
let by_model: Vec<ModelUsage> = by_model_rows.into_iter()
|
||||||
|
.map(|r| {
|
||||||
|
ModelUsage { provider_id: r.provider_id, model_id: r.model_id, request_count: r.request_count, input_tokens: r.input_tokens, output_tokens: r.output_tokens }
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
// 按天统计 (使用 days 参数或默认 30 天)
|
||||||
|
let days = query.days.unwrap_or(30).min(365).max(1) as i64;
|
||||||
|
let from_days = (chrono::Utc::now() - chrono::Duration::days(days))
|
||||||
|
.date_naive()
|
||||||
|
.and_hms_opt(0, 0, 0).unwrap()
|
||||||
|
.and_utc()
|
||||||
|
.to_rfc3339();
|
||||||
|
let daily_sql = "SELECT SUBSTRING(created_at, 1, 10) as day, COUNT(*)::bigint AS request_count, COALESCE(SUM(input_tokens), 0) AS input_tokens, COALESCE(SUM(output_tokens), 0) AS output_tokens
|
||||||
|
FROM usage_records WHERE account_id = $1 AND created_at >= $2
|
||||||
|
GROUP BY SUBSTRING(created_at, 1, 10) ORDER BY day DESC LIMIT $3";
|
||||||
|
let daily_rows: Vec<UsageByDayRow> = sqlx::query_as(daily_sql)
|
||||||
|
.bind(account_id).bind(&from_days).bind(days as i32)
|
||||||
|
.fetch_all(db).await?;
|
||||||
|
let by_day: Vec<DailyUsage> = daily_rows.into_iter()
|
||||||
|
.map(|r| {
|
||||||
|
DailyUsage { date: r.day, request_count: r.request_count, input_tokens: r.input_tokens, output_tokens: r.output_tokens }
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
// 按 group_by 过滤返回
|
||||||
|
let group_by = query.group_by.as_deref();
|
||||||
|
let by_model = if group_by == Some("model") || group_by.is_none() { by_model } else { vec![] };
|
||||||
|
let by_day = if group_by == Some("day") || group_by.is_none() { by_day } else { vec![] };
|
||||||
|
|
||||||
|
Ok(UsageStats {
|
||||||
|
total_requests,
|
||||||
|
total_input_tokens: total_input,
|
||||||
|
total_output_tokens: total_output,
|
||||||
|
by_model,
|
||||||
|
by_day,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn record_usage(
|
||||||
|
db: &PgPool, account_id: &str, provider_id: &str, model_id: &str,
|
||||||
|
input_tokens: i64, output_tokens: i64, latency_ms: Option<i64>,
|
||||||
|
status: &str, error_message: Option<&str>,
|
||||||
|
) -> SaasResult<()> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO usage_records (account_id, provider_id, model_id, input_tokens, output_tokens, latency_ms, status, error_message, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)"
|
||||||
|
)
|
||||||
|
.bind(account_id).bind(provider_id).bind(model_id)
|
||||||
|
.bind(input_tokens).bind(output_tokens).bind(latency_ms)
|
||||||
|
.bind(status).bind(error_message).bind(&now)
|
||||||
|
.execute(db).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Helpers ============
|
||||||
|
|
||||||
|
fn mask_api_key(key: &str) -> String {
|
||||||
|
if key.len() <= 8 {
|
||||||
|
return "*".repeat(key.len());
|
||||||
|
}
|
||||||
|
format!("{}...{}", &key[..4], &key[key.len()-4..])
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user