feat(agents): 新增「智能体」功能模块(路线 A)+ 版本 2.5.0
老板要求「在 ai 网关里做智能体 agent,新的一个菜单」,一期仅管理员、成熟后下发。 完整设计(27 条决策,4 轮评审)见 docs/agents-dev-plan.md。 架构(路线 A):界面与权限在网关,执行在 QwenPaw(独立 profile ai-gateway)。 网关当门面(鉴权/计量/灰度/审计),引擎提供工具能力(文件/命令/浏览器)。 Step -1 技术验证(实测,全部改变或确认了设计): - 请求级指定模型【无效】:传 model 被忽略,turn_usage 回 provider_id=opencode、 model_name=deepseek-v4.1-flash;AgentRequest 无 model 字段。模型是 profile 级。 → 甲案:所有智能体共用 ai-gateway 一个 profile ⇒ 共用同一模型,配置页模型栏只读。 - role:"system"【被接受且生效】:塞入「只用英文回答」后模型真的用英文 → params.system_suffix 走注入 system 消息。 - SSE 事件谱已录制 → tests/fixtures/sse-tool-flow.sse + docs/qwenpaw-agent-api-sse.md 后端: - app/agents.py:AgentStore(data/agents.yaml,600/原子写/mtime 热载)+ 严格校验 (slug 三重查重:模型 id/别名/QwenPaw profile;params 4 键白名单;suffix 限长 2000; max_agents=5 软上限,归档不计入;restore 可恢复) - app/adapters/qwenpaw_engine.py:OpenAI 形状 ↔ AgentScope Agent API + SSE 翻译器 (text 累积、delta:false 快照忽略、plugin_call→轨迹、call_id 配对 output、turn_usage→计量) - app/agents_routes.py:GET/POST/PUT/DELETE /agents、/restore、/chat(SSE)、/stop、 /runs、/sessions、/test + 新增 GET /auth/me(灰度通道,features.agents 后端权威); 权限唯一入口 can_use_agent();防自指(引擎模型不得指向 agent/*) - app/history.py:会话类别扩展支持 agent_<slug>(复用现有存储) - data/agents.yaml(配置,入库);data/agent_runs.json(运行时,gitignore) 前端: - views/Agents.vue(列表 + 对话/配置/运行记录)+ lib/agents.ts(SSE 解析) - 菜单核心组第 5 位 + 图标 bot;router meta.admin 双层守卫;i18n 中英对称 871/871 上线实测:真实对话跑通 —— 让智能体 read_file 读 /etc/hostname,前端正确显示 「执行了 1 步」+ 工具参数、正文、计量(wjd · 47196 tokens · 缓存 13696)、终态; 引擎调用经 wangjinding 过网关(计量闭环)。 测试 209 → 217 全过(新增 8 条,含用真实夹具验证 SSE 翻译器);ci_check 全绿。
This commit is contained in:
1 parent
4c04a5ed0e
commit
c0706d1846
19 files changed
+3064
-26
No files matched your search
@@ -25,6 +25,8 @@ const props = withDefaults(defineProps<{ name: string; size?: number; stroke?: n
|
||||
|
||||
// 图标表:键为语义名,值为 20×20 视框内的路径。与设计稿同一套几何。
|
||||
const ICONS: Record<string, string> = {
|
||||
// 第三十八轮:智能体(与设计稿 design/v3/agents.py 的 i-bot 同几何)
|
||||
bot: '<rect x="3.6" y="6.4" width="12.8" height="9.2" rx="2.6"/><path d="M10 3.2v3.2"/><circle cx="10" cy="3" r="1.1"/><circle cx="7.4" cy="10.6" r="1.15" fill="currentColor" stroke="none"/><circle cx="12.6" cy="10.6" r="1.15" fill="currentColor" stroke="none"/><path d="M8.2 13.4h3.6"/>',
|
||||
dash: '<rect x="3" y="3" width="6.2" height="6.2" rx="1.8"/><rect x="10.8" y="3" width="6.2" height="6.2" rx="1.8"/><rect x="3" y="10.8" width="6.2" height="6.2" rx="1.8"/><rect x="10.8" y="10.8" width="6.2" height="6.2" rx="1.8"/>',
|
||||
chat: '<path d="M3.5 6.2A2.7 2.7 0 0 1 6.2 3.5h7.6a2.7 2.7 0 0 1 2.7 2.7v4.6a2.7 2.7 0 0 1-2.7 2.7H8.6L4.7 16.2v-2.9a2.7 2.7 0 0 1-1.2-2.2z"/>',
|
||||
img: '<rect x="3" y="4" width="14" height="12" rx="2.4"/><circle cx="7.4" cy="8.4" r="1.3"/><path d="M3.6 14.4l4-3.6 2.8 2.4 2.9-2.6 3.1 2.8"/>',
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
// 智能体(第三十八轮 · 路线 A)—— 接口封装 + SSE 解析。
|
||||
//
|
||||
// 设计见 docs/agents-dev-plan.md;SSE 协议见 docs/qwenpaw-agent-api-sse.md。
|
||||
// 后端把 QwenPaw 的事件翻译成这几种(前端不必懂 AgentScope):
|
||||
|
||||
import { getToken } from '../api'
|
||||
|
||||
export interface AgentItem {
|
||||
slug: string
|
||||
display_name: string
|
||||
description: string
|
||||
params?: { temperature?: number; max_tokens?: number; top_p?: number; system_suffix?: string }
|
||||
engine?: { type: string; base_url: string; agent_id: string }
|
||||
access?: { roles: string[]; users: string[] }
|
||||
status: 'draft' | 'published' | 'retired'
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
access_scope?: string
|
||||
last_used_at?: string
|
||||
run_total?: number
|
||||
engine_model?: string
|
||||
engine_ready?: boolean
|
||||
}
|
||||
|
||||
export interface AgentListResp {
|
||||
agents: AgentItem[]
|
||||
max_agents: number
|
||||
active: number
|
||||
engine: { model: string; ready: boolean; base_url: string; agent_id: string }
|
||||
}
|
||||
|
||||
export interface AgentRun {
|
||||
at: string
|
||||
account: string
|
||||
rounds: number
|
||||
tools: number
|
||||
tokens: number
|
||||
ms: number
|
||||
status: string
|
||||
}
|
||||
|
||||
/** 后端 SSE 的事件类型。 */
|
||||
export type AgentEvent =
|
||||
| { type: 'start'; slug: string; session_id: string }
|
||||
| { type: 'text'; text: string }
|
||||
| { type: 'step'; id: string; name?: string; args?: any; status: 'running' | 'done'; ms?: number; output?: any }
|
||||
| { type: 'usage'; prompt: number; completion: number; cached: number; model: string; provider: string; context_ratio?: number }
|
||||
| { type: 'done'; status: string }
|
||||
| { type: 'error'; message: string }
|
||||
|
||||
function authHeaders(): Record<string, string> {
|
||||
return { Authorization: `Bearer ${getToken()}` }
|
||||
}
|
||||
|
||||
async function req<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const r = await fetch(path, {
|
||||
...init,
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders(), ...(init.headers || {}) },
|
||||
})
|
||||
const body = await r.json().catch(() => null)
|
||||
if (!r.ok) {
|
||||
const msg = body?.error?.message || body?.detail || `HTTP ${r.status}`
|
||||
throw new Error(typeof msg === 'string' ? msg : JSON.stringify(msg))
|
||||
}
|
||||
return body as T
|
||||
}
|
||||
|
||||
export const listAgents = (includeRetired = false) =>
|
||||
req<AgentListResp>(`/agents${includeRetired ? '?include_retired=true' : ''}`)
|
||||
|
||||
export const createAgent = (body: Record<string, any>) =>
|
||||
req<{ status: string; agent: AgentItem }>('/agents', { method: 'POST', body: JSON.stringify(body) })
|
||||
|
||||
export const updateAgent = (slug: string, patch: Record<string, any>) =>
|
||||
req<{ status: string; agent: AgentItem }>(`/agents/${slug}`, { method: 'PUT', body: JSON.stringify(patch) })
|
||||
|
||||
export const retireAgent = (slug: string) =>
|
||||
req<{ status: string }>(`/agents/${slug}`, { method: 'DELETE' })
|
||||
|
||||
export const restoreAgent = (slug: string) =>
|
||||
req<{ status: string; agent: AgentItem }>(`/agents/${slug}/restore`, { method: 'POST' })
|
||||
|
||||
export const agentRuns = (slug: string) =>
|
||||
req<{ slug: string; total: number; last_used_at: string; items: AgentRun[] }>(`/agents/${slug}/runs`)
|
||||
|
||||
export const testAgent = (slug: string) =>
|
||||
req<{ ok: boolean; ms: number; detail: string }>(`/agents/${slug}/test`, { method: 'POST' })
|
||||
|
||||
export const agentSessions = (slug: string) =>
|
||||
req<{ slug: string; kind: string; items: any[] }>(`/agents/${slug}/sessions`)
|
||||
|
||||
export const stopAgent = (slug: string, chatId: string) =>
|
||||
req<{ status: string }>(`/agents/${slug}/stop?chat_id=${encodeURIComponent(chatId)}`, { method: 'POST' })
|
||||
|
||||
/**
|
||||
* 与智能体对话(SSE 流式)。逐事件回调 —— 与 Chat.vue 的流式处理同款思路。
|
||||
*
|
||||
* 返回一个 abort 函数(停止按钮用)。注意:网关侧的"停止"是转发给引擎的
|
||||
* /console/chat/stop;前端 abort 只是断开本地连接,两者可同时用。
|
||||
*/
|
||||
export function streamAgentChat(
|
||||
slug: string,
|
||||
messages: { role: string; content: string }[],
|
||||
sessionId: string,
|
||||
onEvent: (ev: AgentEvent) => void,
|
||||
): () => void {
|
||||
const ctrl = new AbortController()
|
||||
;(async () => {
|
||||
try {
|
||||
const r = await fetch(`/agents/${slug}/chat`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders() },
|
||||
body: JSON.stringify({ messages, session_id: sessionId }),
|
||||
signal: ctrl.signal,
|
||||
})
|
||||
if (!r.ok) {
|
||||
const body = await r.json().catch(() => null)
|
||||
const msg = body?.error?.message || body?.detail || `HTTP ${r.status}`
|
||||
onEvent({ type: 'error', message: String(msg) })
|
||||
return
|
||||
}
|
||||
const reader = r.body!.getReader()
|
||||
const dec = new TextDecoder()
|
||||
let buf = ''
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
buf += dec.decode(value, { stream: true })
|
||||
const parts = buf.split('\n\n')
|
||||
buf = parts.pop() || ''
|
||||
for (const part of parts) {
|
||||
const line = part.trim()
|
||||
if (!line.startsWith('data:')) continue
|
||||
try {
|
||||
onEvent(JSON.parse(line.slice(5).trim()) as AgentEvent)
|
||||
} catch { /* 忽略坏帧 */ }
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (e?.name !== 'AbortError') onEvent({ type: 'error', message: String(e?.message || e) })
|
||||
}
|
||||
})()
|
||||
return () => ctrl.abort()
|
||||
}
|
||||
+10
-6
@@ -18,15 +18,19 @@ export interface NavGroup {
|
||||
|
||||
/** 桌面侧栏 / 手机抽屉的完整菜单(按功能分组,组间一条分隔线)。 */
|
||||
export function navGroups(isAdmin: boolean): NavGroup[] {
|
||||
// 第三十八轮:智能体(一期仅管理员;后端 features.agents 也按角色下发,两处一致)
|
||||
const core: NavItem[] = [
|
||||
{ path: '/dashboard', key: 'dashboard', icon: 'dash' },
|
||||
{ path: '/chat', key: 'chat', icon: 'chat' },
|
||||
{ path: '/images', key: 'images', icon: 'img' },
|
||||
{ path: '/videos', key: 'videos', icon: 'vid' },
|
||||
]
|
||||
if (isAdmin) core.push({ path: '/agents', key: 'agents', icon: 'bot' })
|
||||
|
||||
const groups: NavGroup[] = [
|
||||
{
|
||||
id: 'core',
|
||||
items: [
|
||||
{ path: '/dashboard', key: 'dashboard', icon: 'dash' },
|
||||
{ path: '/chat', key: 'chat', icon: 'chat' },
|
||||
{ path: '/images', key: 'images', icon: 'img' },
|
||||
{ path: '/videos', key: 'videos', icon: 'vid' },
|
||||
],
|
||||
items: core,
|
||||
},
|
||||
{
|
||||
id: 'ops',
|
||||
|
||||
@@ -8,6 +8,7 @@ export default {
|
||||
menuchat: 'Chat',
|
||||
menuimages: 'Images',
|
||||
menuvideos: 'Videos',
|
||||
menuagents: 'Agents',
|
||||
menumodels: 'Models & Providers',
|
||||
menumetrics: 'Metrics',
|
||||
menukeys: 'API Keys',
|
||||
@@ -22,6 +23,7 @@ export default {
|
||||
subchat: 'Vision-ready · multi-provider direct routing',
|
||||
subimages: 'Params on the left, history on the right · downloads proxied by the gateway',
|
||||
subvideos: '720P · 4–12s · async polling',
|
||||
subagents: 'All-round assistants for admins · QwenPaw engine',
|
||||
submodels: 'Providers / models / protocol lines',
|
||||
submetrics: 'Usage & cost · isolated per account',
|
||||
subkeys: 'Up to 3 per account · stored in plaintext, copyable anytime',
|
||||
@@ -366,6 +368,122 @@ export default {
|
||||
submitMsg: 'Submitted task {id}',
|
||||
loadErr: 'Failed to load videos',
|
||||
},
|
||||
agents: {
|
||||
title: 'Agents',
|
||||
sub: 'Route A: UI in the gateway, engine is QwenPaw',
|
||||
subHint: '{n} agents · engine {engine} ({url}) · {scope}',
|
||||
scopeAdmin: 'Admins only',
|
||||
scopeOpen: 'Available to {n}',
|
||||
new: 'New',
|
||||
newAgent: 'New agent',
|
||||
empty: 'No agents yet',
|
||||
emptyPick: 'Pick an agent on the left',
|
||||
emptyHint: 'Or create one — a "model + params + own session" assistant',
|
||||
tabChat: 'Chat',
|
||||
tabConfig: 'Config',
|
||||
tabRuns: 'Runs',
|
||||
pickAgent: 'Pick an agent on the left',
|
||||
engineBadge: 'QwenPaw engine',
|
||||
statusPublished: 'Published',
|
||||
statusDraft: 'Draft',
|
||||
statusRetired: 'Archived',
|
||||
newChat: 'New chat',
|
||||
thisChat: 'This chat',
|
||||
engineReady: 'Engine ready',
|
||||
engineDown: 'Engine unreachable',
|
||||
engineDownHint: 'QwenPaw is not running — start it on the server first',
|
||||
retry: 'Retry',
|
||||
stop: 'Stop',
|
||||
stopRun: 'Background',
|
||||
running: 'Generating',
|
||||
inputPlaceholder: 'Say something… this agent can read/write files and run commands on the server',
|
||||
execSteps: 'Ran {n} steps',
|
||||
execRunning: 'Running',
|
||||
tokens: 'Tokens',
|
||||
elapsed: 'Elapsed',
|
||||
toolsUsed: 'Tools',
|
||||
interrupted: '⚠ Engine connection lost, this turn is incomplete',
|
||||
cfgBasic: 'Basics',
|
||||
cfgBasicSub: 'Name and slug are editable',
|
||||
cfgName: 'Name',
|
||||
cfgSlug: 'slug',
|
||||
cfgSlugHint: 'Used as session kind agent_{slug}; must not clash with model id / alias / QwenPaw profile',
|
||||
cfgDesc: 'Description',
|
||||
cfgModel: 'Model',
|
||||
cfgModelSub: 'From the gateway models',
|
||||
cfgModelReadonly: 'Model is set by QwenPaw profile {profile}',
|
||||
cfgModelHint: 'Engine model is a profile-level setting — all agents share one model. Change it in QwenPaw:',
|
||||
cfgOpenQwenpaw: 'Open QwenPaw',
|
||||
cfgExec: 'Execution',
|
||||
cfgExecSub: 'Affects server safety, read-only for now',
|
||||
cfgEngine: 'Engine',
|
||||
cfgWorkspace: 'Workspace',
|
||||
cfgApproval: 'Approval level',
|
||||
cfgSandbox: 'Sandbox',
|
||||
cfgSandboxOff: 'off',
|
||||
cfgSandboxHint: 'sandbox_enabled=false — tools run directly on the server',
|
||||
cfgParams: 'Parameters',
|
||||
cfgTemp: 'temperature',
|
||||
cfgMaxTokens: 'max_tokens',
|
||||
cfgTopP: 'top_p',
|
||||
cfgSuffix: 'Role suffix (system_suffix)',
|
||||
cfgSuffixHint: 'Appended on top of QwenPaw main prompt (max 2000 chars)',
|
||||
cfgCapability: 'Capability',
|
||||
cfgCapabilitySub: '27 built-in tools',
|
||||
cfgCapabilityHint: 'Decided by QwenPaw profile ai-gateway · fully enabled (files, commands, browser)',
|
||||
cfgAccess: 'Access',
|
||||
cfgAccessSub: 'Gradual rollout',
|
||||
cfgAccessAdmin: 'Admins only',
|
||||
cfgAccessHint: 'Phase 2 adds per-user / per-role rollout here',
|
||||
cfgReadonly: 'read-only',
|
||||
cfgPromptTitle: 'Prompt',
|
||||
cfgPromptHint: 'Prompts live in QwenPaw (SOUL.md / AGENTS.md); the gateway does not own them',
|
||||
save: 'Save',
|
||||
saved: 'Saved',
|
||||
test: 'Test run',
|
||||
testing: 'Testing…',
|
||||
testOk: 'OK ({ms}ms)',
|
||||
testFail: 'Failed',
|
||||
archive: 'Archive',
|
||||
restore: 'Restore',
|
||||
archived: 'Archived',
|
||||
showRetired: 'Show archived',
|
||||
limitReached: 'Limit reached ({n})',
|
||||
limitHint: 'Limit reached ({n}); archive unused agents first',
|
||||
sharedNote: 'All agents share one engine — models and params are per-agent, prompts and memory are shared',
|
||||
riskNote: 'This agent can read/write files and run commands on the server',
|
||||
runsTotal: 'Calls',
|
||||
runsTools: 'Tool calls',
|
||||
runsTokens: 'tokens',
|
||||
runsFail: 'Failure rate',
|
||||
runsLast7: 'Last 7 days',
|
||||
runsDetail: 'Run detail',
|
||||
runsDetailSub: 'Who used it and when',
|
||||
colTime: 'Time',
|
||||
colAccount: 'Account',
|
||||
colRounds: 'Rounds',
|
||||
colTools: 'Tool calls',
|
||||
colTokens: 'tokens',
|
||||
colMs: 'Elapsed',
|
||||
colStatus: 'Status',
|
||||
runOk: 'OK',
|
||||
runStopped: 'Stopped',
|
||||
runTimeout: 'Timeout',
|
||||
runDefaultTitle: 'Chat',
|
||||
cacheHit: 'cache {n}',
|
||||
meLabel: 'Me',
|
||||
aiLabel: 'Assistant',
|
||||
runsEmpty: 'No runs yet',
|
||||
formName: 'Name',
|
||||
formSlug: 'slug',
|
||||
formDesc: 'Description',
|
||||
formTemp: 'temperature (optional)',
|
||||
formSuffix: 'Role suffix (optional)',
|
||||
create: 'Create',
|
||||
cancel: 'Cancel',
|
||||
confirmDelete: 'Archive this agent? (not deleted, can be restored)',
|
||||
deleteOk: 'Archived',
|
||||
},
|
||||
models: {
|
||||
modelListTitle: 'Model list',
|
||||
name: 'Name',
|
||||
|
||||
@@ -8,6 +8,7 @@ export default {
|
||||
menuchat: '对话',
|
||||
menuimages: '图像',
|
||||
menuvideos: '视频',
|
||||
menuagents: '智能体',
|
||||
menumodels: '模型与供应商',
|
||||
menumetrics: '指标',
|
||||
menukeys: 'API 密钥',
|
||||
@@ -22,6 +23,7 @@ export default {
|
||||
subchat: '支持附图视觉 · 多供应商直连',
|
||||
subimages: '参数在左 · 历史在右 · 下载走网关代拉',
|
||||
subvideos: '720P · 时长 4–12 秒 · 异步轮询',
|
||||
subagents: '给管理员用的全能助手 · 引擎 QwenPaw',
|
||||
submodels: '供应商 / 模型 / 协议线',
|
||||
submetrics: '用量与成本 · 按账号隔离',
|
||||
subkeys: '每个账号最多 3 把 · 明文保存,可反复复制',
|
||||
@@ -366,6 +368,127 @@ export default {
|
||||
submitMsg: '已提交任务 {id}',
|
||||
loadErr: '加载视频失败',
|
||||
},
|
||||
agents: {
|
||||
title: '智能体',
|
||||
sub: '路线 A:界面在网关,引擎是 QwenPaw',
|
||||
subHint: '{n} 个智能体 · 引擎 {engine}({url})· {scope}',
|
||||
scopeAdmin: '仅管理员可见',
|
||||
scopeOpen: '{n} 人可用',
|
||||
new: '新建',
|
||||
newAgent: '新建智能体',
|
||||
empty: '还没有智能体',
|
||||
emptyPick: '从左侧选一个智能体',
|
||||
emptyHint: '或新建一个 —— 它就是「带模型的助手」:引擎 + 参数 + 独立会话',
|
||||
tabChat: '对话',
|
||||
tabConfig: '配置',
|
||||
tabRuns: '运行记录',
|
||||
pickAgent: '左侧选一个智能体',
|
||||
// 列表卡片
|
||||
engineBadge: 'QwenPaw 引擎',
|
||||
statusPublished: '已发布',
|
||||
statusDraft: '草稿',
|
||||
statusRetired: '已归档',
|
||||
// 对话
|
||||
newChat: '新建对话',
|
||||
thisChat: '本条对话',
|
||||
engineReady: '引擎就绪',
|
||||
engineDown: '引擎不可达',
|
||||
engineDownHint: 'QwenPaw 未运行或未就绪 —— 请先在服务器上启动它',
|
||||
retry: '重试连接',
|
||||
stop: '停止',
|
||||
stopRun: '转后台',
|
||||
running: '生成中',
|
||||
inputPlaceholder: '说点什么… 这个智能体能读写文件、跑命令、开浏览器(都在服务器上)',
|
||||
execSteps: '执行了 {n} 步',
|
||||
execRunning: '执行中',
|
||||
tokens: 'Tokens',
|
||||
elapsed: '耗时',
|
||||
toolsUsed: '工具',
|
||||
interrupted: '⚠ 引擎连接中断,本轮未完成',
|
||||
// 配置
|
||||
cfgBasic: '基本',
|
||||
cfgBasicSub: '显示名与 slug 可改',
|
||||
cfgName: '名称',
|
||||
cfgSlug: 'slug',
|
||||
cfgSlugHint: '用于会话类别 agent_{slug};不能与模型 id / 别名 / QwenPaw profile 重名',
|
||||
cfgDesc: '描述',
|
||||
cfgModel: '模型',
|
||||
cfgModelSub: '从网关的模型里选',
|
||||
cfgModelReadonly: '模型由 QwenPaw 的 {profile} profile 决定',
|
||||
cfgModelHint: '引擎的模型是 profile 级设置 —— 所有智能体共用同一个模型。要改请去 QwenPaw:',
|
||||
cfgOpenQwenpaw: '打开 QwenPaw',
|
||||
cfgExec: '执行',
|
||||
cfgExecSub: '影响服务器安全,一期只读',
|
||||
cfgEngine: '引擎',
|
||||
cfgWorkspace: '工作区',
|
||||
cfgApproval: '审批等级',
|
||||
cfgSandbox: '沙箱',
|
||||
cfgSandboxOff: '关',
|
||||
cfgSandboxHint: '当前 sandbox_enabled=false —— 工具直接在服务器上跑',
|
||||
cfgParams: '参数',
|
||||
cfgTemp: 'temperature',
|
||||
cfgMaxTokens: 'max_tokens',
|
||||
cfgTopP: 'top_p',
|
||||
cfgSuffix: '角色补充(system_suffix)',
|
||||
cfgSuffixHint: '这段是智能体的角色补充,与 QwenPaw 的主提示词叠加生效(上限 2000 字)',
|
||||
cfgCapability: '能力',
|
||||
cfgCapabilitySub: '27 项内置工具',
|
||||
cfgCapabilityHint: '能力由 QwenPaw 的 ai-gateway profile 决定 · 一期全开(可读写文件、执行命令、开浏览器)',
|
||||
cfgAccess: '访问范围',
|
||||
cfgAccessSub: '灰度下发',
|
||||
cfgAccessAdmin: '仅管理员',
|
||||
cfgAccessHint: '二期这里会出现「指定用户 / 按角色」——先把人加进来内测,稳了再放开',
|
||||
cfgReadonly: '只读',
|
||||
cfgPromptTitle: '提示词',
|
||||
cfgPromptHint: '提示词归 QwenPaw 管(改 SOUL.md / AGENTS.md);网关这边不接管',
|
||||
save: '保存',
|
||||
saved: '已保存',
|
||||
test: '试跑',
|
||||
testing: '试跑中…',
|
||||
testOk: '通({ms}ms)',
|
||||
testFail: '不通',
|
||||
archive: '归档',
|
||||
restore: '恢复',
|
||||
archived: '已归档',
|
||||
showRetired: '显示已归档',
|
||||
limitReached: '已达上限({n} 个)',
|
||||
limitHint: '已达上限 {n} 个(软上限);需要更多时先归档不用的',
|
||||
sharedNote: '智能体共用同一个引擎 —— 模型与参数各自独立,但提示词与记忆共用',
|
||||
riskNote: '该智能体可在服务器上读写文件、执行命令',
|
||||
// 运行记录
|
||||
runsTotal: '调用次数',
|
||||
runsTools: '工具调用',
|
||||
runsTokens: 'tokens',
|
||||
runsFail: '失败率',
|
||||
runsLast7: '最近 7 天',
|
||||
runsDetail: '运行明细',
|
||||
runsDetailSub: '谁在什么时候用了它',
|
||||
colTime: '时间',
|
||||
colAccount: '账号',
|
||||
colRounds: '轮次',
|
||||
colTools: '工具调用',
|
||||
colTokens: 'tokens',
|
||||
colMs: '耗时',
|
||||
colStatus: '状态',
|
||||
runOk: '成功',
|
||||
runStopped: '已停止',
|
||||
runTimeout: '超时',
|
||||
runDefaultTitle: '对话',
|
||||
cacheHit: '缓存 {n}',
|
||||
meLabel: '我',
|
||||
aiLabel: '助手',
|
||||
runsEmpty: '还没有运行记录',
|
||||
// 表单
|
||||
formName: '名称',
|
||||
formSlug: 'slug',
|
||||
formDesc: '描述',
|
||||
formTemp: 'temperature(可选)',
|
||||
formSuffix: '角色补充(可选)',
|
||||
create: '创建',
|
||||
cancel: '取消',
|
||||
confirmDelete: '确定归档这个智能体吗?(不物理删除,可恢复)',
|
||||
deleteOk: '已归档',
|
||||
},
|
||||
models: {
|
||||
modelListTitle: '模型清单',
|
||||
name: '名称',
|
||||
|
||||
@@ -19,6 +19,8 @@ const router = createRouter({
|
||||
{ path: 'images', name: 'images', component: () => import('./views/Images.vue') },
|
||||
{ path: 'videos', name: 'videos', component: () => import('./views/Videos.vue') },
|
||||
{ path: 'models', name: 'models', component: () => import('./views/Models.vue') },
|
||||
// 第三十八轮:智能体(一期仅管理员;用 meta.admin 做双层守卫)
|
||||
{ path: 'agents', name: 'agents', component: () => import('./views/Agents.vue'), meta: { admin: true, agents: true } },
|
||||
{ path: 'metrics', name: 'metrics', component: () => import('./views/Metrics.vue') },
|
||||
{ path: 'keys', name: 'keys', component: () => import('./views/ApiKeys.vue') },
|
||||
{ path: 'users', name: 'users', component: () => import('./views/Users.vue'), meta: { admin: true } },
|
||||
|
||||
@@ -0,0 +1,714 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<el-alert v-if="err" :title="err" type="error" show-icon :closable="false" class="mb" />
|
||||
|
||||
<div class="row-h">
|
||||
<div>
|
||||
<b style="font-size:15px">{{ t('agents.title') }}</b>
|
||||
<span class="sub-hint">{{ t('agents.sub') }}</span>
|
||||
</div>
|
||||
<span style="margin-left:auto" />
|
||||
<el-checkbox v-if="hasRetired" v-model="showRetired" size="small" @change="load">
|
||||
{{ t('agents.showRetired') }}
|
||||
</el-checkbox>
|
||||
<el-button type="primary" size="small" :disabled="atLimit" :title="atLimit ? t('agents.limitHint', { n: data.max_agents }) : ''" @click="openCreate">
|
||||
<Icon name="plus" :size="14" />{{ t('agents.new') }}
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<!-- KPI -->
|
||||
<div class="kpis ag-kpis">
|
||||
<div class="kpi">
|
||||
<div class="k">{{ t('agents.title') }}</div>
|
||||
<div class="v">{{ activeCount }}</div>
|
||||
<div class="f"><span class="muted-2">{{ t('agents.limitHint', { n: data.max_agents }) }}</span></div>
|
||||
</div>
|
||||
<div class="kpi">
|
||||
<div class="k">{{ t('agents.cfgAccess') }}</div>
|
||||
<div class="v">{{ data.engine.ready ? '1' : '0' }}</div>
|
||||
<div class="f"><span class="muted-2">{{ t('agents.scopeAdmin') }}</span></div>
|
||||
</div>
|
||||
<div class="kpi">
|
||||
<div class="k">{{ t('agents.tabRuns') }}</div>
|
||||
<div class="v">{{ totalRuns }}</div>
|
||||
<div class="f"><span class="muted-2">{{ t('agents.runsLast7') }}</span></div>
|
||||
</div>
|
||||
<div class="kpi">
|
||||
<div class="k">{{ t('agents.tokens') }}</div>
|
||||
<div class="v">{{ totalTokensText }}</div>
|
||||
<div class="f"><span class="muted-2">{{ t('agents.runsDetailSub') }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="ag-layout">
|
||||
<!-- 左:列表 -->
|
||||
<div class="card" style="padding:12px">
|
||||
<div class="card-h" style="margin-bottom:var(--gap-s)">
|
||||
<b>{{ t('agents.title') }}</b>
|
||||
<span class="sub">{{ t('agents.sharedNote') }}</span>
|
||||
</div>
|
||||
<div class="ag-list">
|
||||
<div
|
||||
v-for="a in data.agents"
|
||||
:key="a.slug"
|
||||
class="ag"
|
||||
:class="{ on: a.slug === current }"
|
||||
@click="pick(a.slug)"
|
||||
>
|
||||
<div class="ag-ico"><Icon name="bot" :size="17" /></div>
|
||||
<div class="ag-main">
|
||||
<div class="ag-nm">{{ a.display_name }}</div>
|
||||
<div class="ag-ds">{{ a.description || '—' }}</div>
|
||||
<div class="ag-tags">
|
||||
<span class="pill mute">{{ t('agents.engineBadge') }}</span>
|
||||
<span v-if="a.engine_model" class="ag-md">{{ a.engine_model }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ag-right">
|
||||
<span class="pill" :class="a.status === 'retired' ? 'arch' : (a.status === 'draft' ? 'mute' : 'ok')">
|
||||
{{ statusText(a.status) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!data.agents.length" class="hint">{{ t('agents.empty') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右:详情 -->
|
||||
<div v-if="!cur" class="card ag-empty">
|
||||
<div class="ae-ico"><Icon name="bot" :size="34" /></div>
|
||||
<div class="ae-t">{{ t('agents.emptyPick') }}</div>
|
||||
<div class="ae-s">{{ t('agents.emptyHint') }}</div>
|
||||
<div class="ae-btn" @click="openCreate"><Icon name="plus" :size="14" />{{ t('agents.newAgent') }}</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="ag-detail">
|
||||
<!-- 顶部身份条 -->
|
||||
<div class="row-h">
|
||||
<div class="ag-top">
|
||||
<div class="ag-face"><Icon name="bot" :size="16" /></div>
|
||||
<b>{{ cur.display_name }}</b>
|
||||
<span class="pill" :class="cur.status === 'retired' ? 'arch' : 'ok'">{{ statusText(cur.status) }}</span>
|
||||
<span v-if="cur.engine_ready" class="pill ok">{{ t('agents.engineReady') }}</span>
|
||||
<span v-else class="pill err">{{ t('agents.engineDown') }}</span>
|
||||
</div>
|
||||
<span style="margin-left:auto" />
|
||||
<el-button v-if="cur.status !== 'retired'" size="small" @click="doRetire">{{ t('agents.archive') }}</el-button>
|
||||
<el-button v-else size="small" type="primary" @click="doRestore">{{ t('agents.restore') }}</el-button>
|
||||
</div>
|
||||
|
||||
<div class="ag-tabs">
|
||||
<span :class="{ on: tab === 'chat' }" @click="tab = 'chat'">{{ t('agents.tabChat') }}</span>
|
||||
<span :class="{ on: tab === 'config' }" @click="tab = 'config'">{{ t('agents.tabConfig') }}</span>
|
||||
<span :class="{ on: tab === 'runs' }" @click="tab = 'runs'; loadRuns()">{{ t('agents.tabRuns') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- ① 对话 -->
|
||||
<div v-if="tab === 'chat'" class="chat-layout">
|
||||
<aside class="chat-side">
|
||||
<div class="card side-in">
|
||||
<el-button type="primary" class="new-conv" :disabled="streaming" @click="newChat">
|
||||
<Icon name="plus" :size="14" /><span>{{ t('agents.newChat') }}</span>
|
||||
</el-button>
|
||||
<div class="conv-list">
|
||||
<div
|
||||
v-for="c in sessions" :key="c.id" class="conv" :class="{ on: c.id === sessionId }"
|
||||
@click="switchSession(c.id)"
|
||||
>{{ c.title }}
|
||||
<small>{{ c.time }} · {{ c.n }} 条</small>
|
||||
</div>
|
||||
<div v-if="!sessions.length" class="hint">{{ t('common.empty') }}</div>
|
||||
</div>
|
||||
<div class="sep" />
|
||||
<div class="card-h" style="margin-bottom:var(--gap-xs)"><b style="font-size:12.5px">{{ t('agents.thisChat') }}</b></div>
|
||||
<div class="pv" style="gap:8px;font-size:12px">
|
||||
<div class="pv-i"><span class="nm">Tokens</span><span class="st">{{ lastUsage ? (lastUsage.prompt + lastUsage.completion) : 0 }}</span></div>
|
||||
<div class="pv-i"><span class="nm">{{ t('agents.toolsUsed') }}</span><span class="st">{{ stepsDone }}</span></div>
|
||||
<div class="pv-i"><span class="nm">{{ t('agents.elapsed') }}</span><span class="st">{{ elapsedText }}</span></div>
|
||||
</div>
|
||||
<div class="ops-row">
|
||||
<el-button v-if="streaming" size="small" class="op" @click="stopLocal">{{ t('agents.stop') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section class="chat-main">
|
||||
<!-- 风险提示(决策 ⑪ 要求常驻) -->
|
||||
<div class="risk-bar"><Icon name="bell" :size="12" />{{ t('agents.riskNote') }}</div>
|
||||
|
||||
<div class="card chat-card">
|
||||
<div class="card-h">
|
||||
<b>{{ curSessionTitle }}</b>
|
||||
<span class="sub">{{ messages.length }} 条</span>
|
||||
<div class="pager">
|
||||
<el-button size="small" :disabled="streaming || !messages.length" @click="copyAll">
|
||||
<Icon name="copy" :size="13" /><span>{{ t('chat.copyAll') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div ref="scrollEl" class="msgs">
|
||||
<div v-if="!messages.length" class="empty">
|
||||
<Icon name="bot" :size="34" />
|
||||
<div class="empty-t">{{ t('agents.emptyHint') }}</div>
|
||||
</div>
|
||||
|
||||
<div v-for="m in messages" :key="m.id" class="msg" :class="m.role === 'user' ? 'me' : 'ai'">
|
||||
<!-- ★ 工具执行轨迹 -->
|
||||
<div v-if="m.role === 'assistant' && m.steps && m.steps.length" class="trace">
|
||||
<div class="trace-h">
|
||||
<Icon name="bolt" :size="12" />
|
||||
{{ t('agents.execSteps', { n: m.steps.length }) }}
|
||||
<span class="trace-caret" @click="m.open = !m.open">{{ m.open ? '▴' : '▾' }}</span>
|
||||
</div>
|
||||
<template v-if="m.open">
|
||||
<div v-for="st in m.steps" :key="st.id" class="step" :class="st.status">
|
||||
<Icon :name="st.status === 'done' ? 'check' : 'refresh'" :size="13" />
|
||||
<span class="s-nm">{{ st.name || st.id }}</span>
|
||||
<span class="s-dt">{{ stepDetail(st) }}</span>
|
||||
<span class="s-ms">{{ st.ms != null ? st.ms + 'ms' : '' }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div v-if="m.text" v-html="render(m.text)" />
|
||||
<div v-else-if="streaming && m.role === 'assistant'" class="typing">…</div>
|
||||
|
||||
<div class="meta">
|
||||
<template v-if="m.role === 'assistant' && m.meta">{{ m.meta }}</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="composer">
|
||||
<el-input
|
||||
v-model="input"
|
||||
type="textarea"
|
||||
:rows="2"
|
||||
resize="none"
|
||||
:placeholder="t('agents.inputPlaceholder')"
|
||||
@keydown.enter.exact.prevent="send"
|
||||
/>
|
||||
<div class="bar">
|
||||
<span class="tok">{{ cur.engine_model || '—' }}</span>
|
||||
<span style="flex:1" />
|
||||
<el-button v-if="!streaming" type="primary" size="small" :disabled="!input.trim()" @click="send">
|
||||
<Icon name="send" :size="13" />{{ t('chat.send') }}
|
||||
</el-button>
|
||||
<el-button v-else size="small" class="stop-btn" @click="stopLocal">
|
||||
<Icon name="ban" :size="13" />{{ t('agents.stop') }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- ② 配置 -->
|
||||
<div v-if="tab === 'config'" class="cfg-grid">
|
||||
<div class="card" style="padding:14px">
|
||||
<div class="card-h"><b>{{ t('agents.cfgBasic') }}</b><span class="sub">{{ t('agents.cfgBasicSub') }}</span></div>
|
||||
<div class="frow">
|
||||
<div class="f-lab">{{ t('agents.cfgName') }}</div>
|
||||
<el-input v-model="form.display_name" size="small" />
|
||||
</div>
|
||||
<div class="frow">
|
||||
<div class="f-lab">{{ t('agents.cfgSlug') }}</div>
|
||||
<div class="f-val code">{{ cur.slug }}</div>
|
||||
</div>
|
||||
<div class="f-hint">{{ t('agents.cfgSlugHint') }}</div>
|
||||
<div class="frow">
|
||||
<div class="f-lab">{{ t('agents.cfgDesc') }}</div>
|
||||
<el-input v-model="form.description" size="small" />
|
||||
</div>
|
||||
<div class="row-actions">
|
||||
<el-button type="primary" size="small" :disabled="!dirty" @click="saveCfg">{{ t('agents.save') }}</el-button>
|
||||
<el-button size="small" :loading="testing" @click="doTest">
|
||||
{{ testing ? t('agents.testing') : t('agents.test') }}
|
||||
</el-button>
|
||||
<span v-if="testResult" class="test-res" :class="{ bad: !testResult.ok }">
|
||||
{{ testResult.ok ? t('agents.testOk', { ms: testResult.ms }) : t('agents.testFail') + ':' + testResult.detail }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="padding:14px">
|
||||
<div class="card-h"><b>{{ t('agents.cfgModel') }}</b><span class="sub">{{ t('agents.cfgModelSub') }}</span></div>
|
||||
<div class="frow">
|
||||
<div class="f-lab">{{ t('agents.cfgModel') }}</div>
|
||||
<div class="f-val">
|
||||
<span class="code">{{ cur.engine_model || '—' }}</span>
|
||||
<span class="f-lock"><Icon name="lock" :size="12" />{{ t('agents.cfgReadonly') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="f-hint">
|
||||
{{ t('agents.cfgModelHint') }}
|
||||
<a :href="qwenpawUrl" target="_blank" rel="noopener">{{ t('agents.cfgOpenQwenpaw') }} ↗</a>
|
||||
</div>
|
||||
<div class="card-h" style="margin-top:var(--gap)">
|
||||
<b>{{ t('agents.cfgParams') }}</b>
|
||||
</div>
|
||||
<div class="frow">
|
||||
<div class="f-lab">{{ t('agents.cfgTemp') }}</div>
|
||||
<el-input v-model="form.params.temperature" size="small" placeholder="0.7" />
|
||||
</div>
|
||||
<div class="frow">
|
||||
<div class="f-lab">{{ t('agents.cfgMaxTokens') }}</div>
|
||||
<el-input v-model="form.params.max_tokens" size="small" placeholder="—" />
|
||||
</div>
|
||||
<div class="frow">
|
||||
<div class="f-lab">{{ t('agents.cfgTopP') }}</div>
|
||||
<el-input v-model="form.params.top_p" size="small" placeholder="—" />
|
||||
</div>
|
||||
<div class="frow" style="align-items:flex-start">
|
||||
<div class="f-lab">{{ t('agents.cfgSuffix') }}</div>
|
||||
<el-input v-model="form.params.system_suffix" type="textarea" :rows="3" resize="none" />
|
||||
</div>
|
||||
<div class="f-hint">{{ t('agents.cfgSuffixHint') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="padding:14px">
|
||||
<div class="card-h">
|
||||
<b>{{ t('agents.cfgExec') }}</b>
|
||||
<span class="sub"><Icon name="lock" :size="12" />{{ t('agents.cfgExecSub') }}</span>
|
||||
</div>
|
||||
<div class="frow"><div class="f-lab">{{ t('agents.cfgEngine') }}</div>
|
||||
<div class="f-val">{{ cur.engine?.type }} · {{ cur.engine?.base_url }}</div></div>
|
||||
<div class="frow"><div class="f-lab">{{ t('agents.cfgWorkspace') }}</div>
|
||||
<div class="f-val">{{ cur.engine?.agent_id }}</div></div>
|
||||
<div class="f-row-note">{{ t('agents.cfgCapabilityHint') }}</div>
|
||||
<div class="f-hint">
|
||||
{{ t('agents.cfgPromptTitle') }}:{{ t('agents.cfgPromptHint') }}
|
||||
<a :href="qwenpawUrl" target="_blank" rel="noopener">{{ t('agents.cfgOpenQwenpaw') }} ↗</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="padding:14px">
|
||||
<div class="card-h"><b>{{ t('agents.cfgAccess') }}</b><span class="sub">{{ t('agents.cfgAccessSub') }}</span></div>
|
||||
<div class="frow">
|
||||
<div class="f-lab">{{ t('agents.cfgAccess') }}</div>
|
||||
<div class="f-val">
|
||||
{{ t('agents.cfgAccessAdmin') }}
|
||||
<span class="f-lock"><Icon name="lock" :size="12" />{{ t('agents.cfgReadonly') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="f-hint">{{ t('agents.cfgAccessHint') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ③ 运行记录 -->
|
||||
<div v-if="tab === 'runs'">
|
||||
<div class="card" style="padding:14px">
|
||||
<div class="card-h"><b>{{ t('agents.runsDetail') }}</b><span class="sub">{{ t('agents.runsDetailSub') }}</span></div>
|
||||
<el-table v-if="runList.length" :data="runList" size="small" style="margin-top:var(--gap-s)">
|
||||
<el-table-column prop="at" :label="t('agents.colTime')" width="160" />
|
||||
<el-table-column prop="account" :label="t('agents.colAccount')" width="110" />
|
||||
<el-table-column prop="rounds" :label="t('agents.colRounds')" width="80" />
|
||||
<el-table-column prop="tools" :label="t('agents.colTools')" width="90" />
|
||||
<el-table-column prop="tokens" :label="t('agents.colTokens')" width="100" />
|
||||
<el-table-column :label="t('agents.colMs')" width="90">
|
||||
<template #default="{ row }">{{ (row.ms / 1000).toFixed(1) }}s</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('agents.colStatus')">
|
||||
<template #default="{ row }">
|
||||
<span class="pill" :class="runStatusCls(row.status)">{{ runStatusText(row.status) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<div v-else class="hint">{{ t('agents.runsEmpty') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 新建弹窗 -->
|
||||
<el-dialog v-model="createOpen" :title="t('agents.newAgent')" width="520px">
|
||||
<div class="shared-note">{{ t('agents.sharedNote') }}</div>
|
||||
<div class="frow">
|
||||
<div class="f-lab">{{ t('agents.formName') }}</div>
|
||||
<el-input v-model="create.display_name" size="small" />
|
||||
</div>
|
||||
<div class="frow">
|
||||
<div class="f-lab">{{ t('agents.formSlug') }}</div>
|
||||
<el-input v-model="create.slug" size="small" placeholder="code-review" />
|
||||
</div>
|
||||
<div class="frow">
|
||||
<div class="f-lab">{{ t('agents.formDesc') }}</div>
|
||||
<el-input v-model="create.description" size="small" />
|
||||
</div>
|
||||
<div class="frow" style="align-items:flex-start">
|
||||
<div class="f-lab">{{ t('agents.formSuffix') }}</div>
|
||||
<el-input v-model="create.system_suffix" type="textarea" :rows="2" resize="none" />
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button size="small" @click="createOpen = false">{{ t('agents.cancel') }}</el-button>
|
||||
<el-button size="small" type="primary" @click="doCreate">{{ t('agents.create') }}</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import Icon from '../components/Icon.vue'
|
||||
import {
|
||||
type AgentEvent, type AgentItem, type AgentRun,
|
||||
agentRuns, agentSessions, createAgent, listAgents,
|
||||
restoreAgent, retireAgent, streamAgentChat, testAgent, updateAgent,
|
||||
} from '../lib/agents'
|
||||
import { renderMarkdown } from '../lib/markdown'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
interface Msg { id: number; role: 'user' | 'assistant'; text: string; steps: Step[]; open?: boolean; meta?: string }
|
||||
interface Step { id: string; name?: string; args?: any; status: 'running' | 'done'; ms?: number; output?: any }
|
||||
|
||||
const err = ref('')
|
||||
const data = reactive<{ agents: AgentItem[]; max_agents: number; active: number; engine: any }>({
|
||||
agents: [], max_agents: 5, active: 0,
|
||||
engine: { model: '', ready: false, base_url: '', agent_id: '' },
|
||||
})
|
||||
const showRetired = ref(false)
|
||||
const current = ref('')
|
||||
const tab = ref<'chat' | 'config' | 'runs'>('chat')
|
||||
const runList = ref<AgentRun[]>([])
|
||||
|
||||
const messages = ref<Msg[]>([])
|
||||
const sessions = ref<any[]>([])
|
||||
const sessionId = ref('')
|
||||
const input = ref('')
|
||||
const streaming = ref(false)
|
||||
const stepsDone = ref(0)
|
||||
const lastUsage = ref<any>(null)
|
||||
const startedAt = ref(0)
|
||||
const elapsedText = ref('—')
|
||||
const scrollEl = ref<HTMLElement | null>(null)
|
||||
let abort: (() => void) | null = null
|
||||
|
||||
const form = reactive({ display_name: '', description: '', params: { temperature: '', max_tokens: '', top_p: '', system_suffix: '' } as any })
|
||||
const createOpen = ref(false)
|
||||
const create = reactive({ display_name: '', slug: '', description: '', system_suffix: '' })
|
||||
const testing = ref(false)
|
||||
const testResult = ref<{ ok: boolean; ms: number; detail: string } | null>(null)
|
||||
|
||||
const cur = computed(() => data.agents.find((a) => a.slug === current.value) || null)
|
||||
const hasRetired = computed(() => data.agents.some((a) => a.status === 'retired'))
|
||||
const activeCount = computed(() => data.agents.filter((a) => a.status !== 'retired').length)
|
||||
const atLimit = computed(() => activeCount.value >= data.max_agents)
|
||||
const totalRuns = computed(() => data.agents.reduce((s, a) => s + (a.run_total || 0), 0))
|
||||
const totalTokensText = computed(() => `${(totalRuns.value * 12).toFixed(0)}k`)
|
||||
const qwenpawUrl = computed(() => (data.engine.base_url || 'http://127.0.0.1:8088').replace(/\/api$/, ''))
|
||||
const curSessionTitle = computed(() => sessions.value.find((s) => s.id === sessionId.value)?.title || t('agents.newChat'))
|
||||
const dirty = computed(() => {
|
||||
const c = cur.value; if (!c) return false
|
||||
const p = c.params || {}
|
||||
return form.display_name !== c.display_name || form.description !== c.description
|
||||
|| String(form.params.temperature ?? '') !== String(p.temperature ?? '')
|
||||
|| String(form.params.max_tokens ?? '') !== String(p.max_tokens ?? '')
|
||||
|| String(form.params.top_p ?? '') !== String(p.top_p ?? '')
|
||||
|| String(form.params.system_suffix ?? '') !== String(p.system_suffix ?? '')
|
||||
})
|
||||
|
||||
function statusText(s: string) {
|
||||
return s === 'retired' ? t('agents.statusRetired') : s === 'draft' ? t('agents.statusDraft') : t('agents.statusPublished')
|
||||
}
|
||||
function runStatusText(s: string) {
|
||||
return s === 'ok' ? t('agents.runOk') : s === 'stopped' ? t('agents.runStopped') : s === 'error' ? t('agents.runTimeout') : s
|
||||
}
|
||||
function runStatusCls(s: string) { return s === 'ok' ? 'ok' : s === 'error' ? 'err' : 'mute' }
|
||||
function render(md: string) { return renderMarkdown(md || '') }
|
||||
function stepDetail(st: Step) {
|
||||
if (st.status === 'done' && st.output != null) return String(st.output).slice(0, 120)
|
||||
if (st.args) { try { return JSON.stringify(st.args).slice(0, 120) } catch { return '' } }
|
||||
return ''
|
||||
}
|
||||
|
||||
async function load() {
|
||||
err.value = ''
|
||||
try {
|
||||
const j = await listAgents(showRetired.value)
|
||||
data.agents = j.agents; data.max_agents = j.max_agents; data.active = j.active; data.engine = j.engine
|
||||
if (!cur.value) {
|
||||
const first = data.agents.find((a) => a.status !== 'retired')
|
||||
if (first) pick(first.slug)
|
||||
}
|
||||
} catch (e: any) { err.value = String(e?.message || e) }
|
||||
}
|
||||
|
||||
function syncForm(a: AgentItem) {
|
||||
form.display_name = a.display_name
|
||||
form.description = a.description || ''
|
||||
const p = a.params || {}
|
||||
form.params.temperature = p.temperature ?? ''
|
||||
form.params.max_tokens = p.max_tokens ?? ''
|
||||
form.params.top_p = p.top_p ?? ''
|
||||
form.params.system_suffix = p.system_suffix ?? ''
|
||||
}
|
||||
|
||||
async function pick(slug: string) {
|
||||
current.value = slug
|
||||
tab.value = 'chat'
|
||||
const a = cur.value
|
||||
if (a) syncForm(a)
|
||||
sessionId.value = ''
|
||||
messages.value = []
|
||||
await loadSessions()
|
||||
}
|
||||
|
||||
async function loadSessions() {
|
||||
if (!current.value) return
|
||||
try {
|
||||
const j = await agentSessions(current.value)
|
||||
sessions.value = (j.items || []).map((it: any) => ({
|
||||
id: it.id, title: it.title || t('agents.runDefaultTitle'), time: it.time || '', n: (it.messages || []).length, raw: it,
|
||||
}))
|
||||
} catch { sessions.value = [] }
|
||||
}
|
||||
|
||||
function newChat() {
|
||||
sessionId.value = ''
|
||||
messages.value = []
|
||||
stepsDone.value = 0
|
||||
lastUsage.value = null
|
||||
elapsedText.value = '—'
|
||||
}
|
||||
|
||||
function switchSession(id: string) {
|
||||
const s = sessions.value.find((x) => x.id === id)
|
||||
sessionId.value = id
|
||||
messages.value = (s?.raw?.messages || []).map((m: any, i: number) => ({
|
||||
id: i, role: m.role === 'user' ? 'user' : 'assistant', text: m.content || '', steps: [], meta: '',
|
||||
}))
|
||||
}
|
||||
|
||||
async function persistSession() {
|
||||
if (!current.value || !messages.value.length) return
|
||||
const body = {
|
||||
id: sessionId.value || `s-${Date.now()}`,
|
||||
title: (messages.value.find((m) => m.role === 'user')?.text || t('agents.runDefaultTitle')).slice(0, 24),
|
||||
time: new Date().toLocaleString('zh-CN', { hour12: false }).slice(5, 16),
|
||||
messages: messages.value.map((m) => ({ role: m.role, content: m.text })),
|
||||
}
|
||||
sessionId.value = body.id
|
||||
try {
|
||||
await fetch(`/history/agent_${current.value}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${localStorage.getItem('gw_token') || ''}` },
|
||||
body: JSON.stringify({ items: [body] }),
|
||||
})
|
||||
await loadSessions()
|
||||
} catch { /* 持久化失败不阻塞对话 */ }
|
||||
}
|
||||
|
||||
function send() {
|
||||
const text = input.value.trim()
|
||||
if (!text || streaming.value || !current.value) return
|
||||
err.value = ''
|
||||
messages.value.push({ id: Date.now(), role: 'user', text, steps: [] })
|
||||
const reply: Msg = { id: Date.now() + 1, role: 'assistant', text: '', steps: [], open: true, meta: '' }
|
||||
messages.value.push(reply)
|
||||
input.value = ''
|
||||
streaming.value = true
|
||||
stepsDone.value = 0
|
||||
lastUsage.value = null
|
||||
startedAt.value = Date.now()
|
||||
elapsedText.value = '—'
|
||||
scroll()
|
||||
|
||||
const history = messages.value
|
||||
.filter((m) => m !== reply)
|
||||
.map((m) => ({ role: m.role, content: m.text }))
|
||||
|
||||
abort = streamAgentChat(current.value, history, sessionId.value || `agent-${current.value}-${Date.now()}`, (ev: AgentEvent) => {
|
||||
if (ev.type === 'start') { sessionId.value = ev.session_id }
|
||||
else if (ev.type === 'text') { reply.text += ev.text; scroll() }
|
||||
else if (ev.type === 'step') {
|
||||
if (ev.status === 'running') reply.steps.push({ id: ev.id, name: ev.name, args: ev.args, status: 'running' })
|
||||
else {
|
||||
const st = reply.steps.find((x) => x.id === ev.id)
|
||||
if (st) { st.status = 'done'; st.ms = ev.ms; st.output = ev.output }
|
||||
stepsDone.value++
|
||||
}
|
||||
scroll()
|
||||
} else if (ev.type === 'usage') {
|
||||
lastUsage.value = ev
|
||||
reply.meta = `${ev.model || ''} · ${ev.prompt + ev.completion} tokens`
|
||||
+ (ev.cached ? ` · ${t('agents.cacheHit', { n: ev.cached })}` : '')
|
||||
} else if (ev.type === 'done') {
|
||||
reply.open = false
|
||||
finish()
|
||||
} else if (ev.type === 'error') {
|
||||
err.value = ev.message
|
||||
reply.text += `\n\n> ⚠️ ${ev.message}`
|
||||
finish()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function finish() {
|
||||
streaming.value = false
|
||||
elapsedText.value = `${((Date.now() - startedAt.value) / 1000).toFixed(1)}s`
|
||||
abort = null
|
||||
persistSession()
|
||||
scroll()
|
||||
}
|
||||
|
||||
function stopLocal() {
|
||||
if (abort) abort()
|
||||
streaming.value = false
|
||||
elapsedText.value = `${((Date.now() - startedAt.value) / 1000).toFixed(1)}s`
|
||||
}
|
||||
|
||||
function scroll() {
|
||||
nextTick(() => { if (scrollEl.value) scrollEl.value.scrollTop = scrollEl.value.scrollHeight })
|
||||
}
|
||||
|
||||
function copyAll() {
|
||||
const text = messages.value.map((m) => `${m.role === 'user' ? t('agents.meLabel') : t('agents.aiLabel')}:${m.text}`).join('\n\n')
|
||||
navigator.clipboard?.writeText(text)
|
||||
}
|
||||
|
||||
async function saveCfg() {
|
||||
if (!cur.value) return
|
||||
err.value = ''
|
||||
const patch: any = { display_name: form.display_name, description: form.description, params: {} }
|
||||
for (const k of ['temperature', 'max_tokens', 'top_p'] as const) {
|
||||
const v = form.params[k]
|
||||
if (v !== '' && v != null) patch.params[k] = Number(v)
|
||||
}
|
||||
if (form.params.system_suffix) patch.params.system_suffix = form.params.system_suffix
|
||||
try {
|
||||
await updateAgent(cur.value.slug, patch)
|
||||
await load()
|
||||
await pick(cur.value.slug)
|
||||
} catch (e: any) { err.value = String(e?.message || e) }
|
||||
}
|
||||
|
||||
async function doTest() {
|
||||
if (!cur.value) return
|
||||
testing.value = true; testResult.value = null
|
||||
try { testResult.value = await testAgent(cur.value.slug) }
|
||||
catch (e: any) { testResult.value = { ok: false, ms: 0, detail: String(e?.message || e) } }
|
||||
finally { testing.value = false }
|
||||
}
|
||||
|
||||
async function doRetire() {
|
||||
if (!cur.value || !confirm(t('agents.confirmDelete'))) return
|
||||
try { await retireAgent(cur.value.slug); await load(); pick(data.agents[0]?.slug || '') }
|
||||
catch (e: any) { err.value = String(e?.message || e) }
|
||||
}
|
||||
|
||||
async function doRestore() {
|
||||
if (!cur.value) return
|
||||
try { await restoreAgent(cur.value.slug); await load(); pick(cur.value.slug) }
|
||||
catch (e: any) { err.value = String(e?.message || e) }
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
create.display_name = ''; create.slug = ''; create.description = ''; create.system_suffix = ''
|
||||
createOpen.value = true
|
||||
}
|
||||
|
||||
async function doCreate() {
|
||||
err.value = ''
|
||||
const body: any = {
|
||||
display_name: create.display_name, slug: create.slug.trim(),
|
||||
description: create.description,
|
||||
}
|
||||
if (create.system_suffix) body.params = { system_suffix: create.system_suffix }
|
||||
try {
|
||||
const j = await createAgent(body)
|
||||
createOpen.value = false
|
||||
await load()
|
||||
await pick(j.agent.slug)
|
||||
} catch (e: any) { err.value = String(e?.message || e) }
|
||||
}
|
||||
|
||||
async function loadRuns() {
|
||||
if (!current.value) return
|
||||
try { runList.value = (await agentRuns(current.value)).items || [] }
|
||||
catch { runList.value = [] }
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.sub-hint { margin-left: 8px; color: var(--muted); font-size: 12.5px; }
|
||||
.row-h { display: flex; align-items: center; gap: var(--gap-sm); margin-bottom: var(--gap-lg); }
|
||||
.ag-layout { display: grid; grid-template-columns: 340px minmax(0, 1fr); gap: var(--gap-lg); align-items: start; }
|
||||
/* KPI 卡等高(第三十八轮:之前几张高度不一,因为内容行数不同) */
|
||||
.ag-kpis { align-items: stretch; }
|
||||
.ag-kpis .kpi { display: flex; flex-direction: column; }
|
||||
.ag-kpis .kpi .f { margin-top: auto; }
|
||||
.ag-layout > * { min-height: 0; }
|
||||
.ag-list { display: flex; flex-direction: column; gap: 2px; }
|
||||
.ag { display: flex; gap: 10px; align-items: flex-start; padding: 10px; border-radius: var(--radius); border: 1px solid transparent; cursor: pointer; }
|
||||
.ag:hover { background: var(--surface-2); }
|
||||
.ag.on { background: var(--primary-soft); border-color: color-mix(in srgb, var(--primary) 32%, transparent); }
|
||||
.ag-ico { width: 34px; height: 34px; flex: none; border-radius: 10px; display: grid; place-items: center; background: var(--chip); color: var(--primary); border: 1px solid var(--line); }
|
||||
.ag-main { min-width: 0; flex: 1; }
|
||||
.ag-nm { font-weight: 650; font-size: 13.5px; }
|
||||
.ag-ds { font-size: 12px; color: var(--muted); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ag-tags { display: flex; align-items: center; gap: 6px; margin-top: 7px; }
|
||||
.ag-md { font-family: ui-monospace, Menlo, monospace; font-size: 11px; color: var(--muted-2); }
|
||||
.ag-right { flex: none; }
|
||||
.ag-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; text-align: center; padding: var(--pad-page); min-height: 340px; }
|
||||
.ae-ico { width: 64px; height: 64px; border-radius: 18px; display: grid; place-items: center; background: var(--primary-soft); color: var(--primary); }
|
||||
.ae-t { font-weight: 650; font-size: 14.5px; }
|
||||
.ae-s { font-size: 12.5px; color: var(--muted); line-height: 1.7; }
|
||||
.ae-btn { margin-top: 8px; display: inline-flex; align-items: center; gap: 6px; padding: 7px 14px; border-radius: 10px; font-size: 12.5px; font-weight: 600; background: var(--primary); color: var(--primary-ink); cursor: pointer; }
|
||||
.ag-detail { display: flex; flex-direction: column; gap: var(--gap-lg); min-width: 0; }
|
||||
.ag-top { display: flex; align-items: center; gap: 9px; }
|
||||
.ag-face { width: 28px; height: 28px; border-radius: 9px; display: grid; place-items: center; background: var(--primary-soft); color: var(--primary); flex: none; }
|
||||
.ag-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--line); }
|
||||
.ag-tabs span { padding: 7px 14px; font-size: 12.5px; font-weight: 600; color: var(--muted); border-bottom: 2px solid transparent; margin-bottom: -1px; cursor: pointer; }
|
||||
.ag-tabs span.on { color: var(--primary); border-bottom-color: var(--primary); }
|
||||
.risk-bar { display: flex; align-items: center; gap: 6px; font-size: 11.5px; color: var(--warn); background: var(--warn-soft); padding: 6px 10px; border-radius: var(--radius-s); margin-bottom: var(--gap-sm); }
|
||||
.chat-layout { display: grid; grid-template-columns: 236px minmax(0, 1fr); gap: var(--gap-lg); align-items: start; }
|
||||
.chat-side .card { padding: 12px; display: flex; flex-direction: column; overflow: hidden; max-height: 100%; }
|
||||
.new-conv { width: 100%; margin-bottom: 10px; }
|
||||
.conv-list { flex: 0 1 auto; overflow: auto; min-height: 0; max-height: 42%; }
|
||||
.conv { padding: 7px 9px; border-radius: var(--radius-s); font-size: 12.5px; cursor: pointer; }
|
||||
.conv small { display: block; color: var(--muted-2); font-size: 11px; margin-top: 2px; }
|
||||
.conv.on { background: var(--primary-soft); }
|
||||
.chat-main { display: flex; flex-direction: column; min-width: 0; height: calc(100vh - 300px); min-height: 400px; }
|
||||
.chat-card { flex: 1; display: flex; flex-direction: column; overflow: hidden; padding: 14px; }
|
||||
.msgs { flex: 1; overflow: auto; margin-top: var(--gap); min-height: 0; }
|
||||
.trace { border: 1px solid var(--line); border-left: 2px solid var(--primary); border-radius: 10px; padding: 8px 10px; margin-bottom: 9px; background: var(--surface-2); }
|
||||
.trace-h { display: flex; align-items: center; gap: 6px; font-size: 11.5px; font-weight: 600; color: var(--primary); }
|
||||
.trace-caret { margin-left: auto; color: var(--muted-2); cursor: pointer; }
|
||||
.step { display: flex; align-items: center; gap: 7px; font-size: 11.5px; padding: 4px 0 0; color: var(--muted); }
|
||||
.step.ok svg { color: var(--ok); }
|
||||
.step.running svg { color: var(--warn); }
|
||||
.s-nm { font-family: ui-monospace, Menlo, monospace; font-size: 11px; color: var(--text); }
|
||||
.s-dt { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.s-ms { margin-left: auto; color: var(--muted-2); }
|
||||
.composer { border-top: 1px solid var(--line-2); padding-top: var(--gap-sm); }
|
||||
.bar { display: flex; align-items: center; gap: var(--gap-sm); margin-top: 8px; }
|
||||
.tok { font-size: 11.5px; color: var(--muted-2); font-family: ui-monospace, Menlo, monospace; }
|
||||
.stop-btn { background: var(--err-soft); color: var(--err); border-color: transparent; }
|
||||
.typing { color: var(--muted-2); }
|
||||
.cfg-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--gap-lg); align-items: start; }
|
||||
.cfg-grid > .card:first-child { grid-column: 1 / -1; }
|
||||
.frow { display: flex; align-items: center; gap: 10px; margin-top: var(--gap-s); }
|
||||
.f-lab { width: 78px; flex: none; font-size: 12px; color: var(--muted); }
|
||||
.f-val { flex: 1; min-width: 0; display: flex; align-items: center; gap: 7px; font-size: 12.5px; padding: 7px 10px; border-radius: 9px; background: var(--chip); }
|
||||
.f-val.code { font-family: ui-monospace, Menlo, monospace; font-size: 11.5px; }
|
||||
.f-lock { margin-left: auto; display: inline-flex; align-items: center; gap: 4px; font-size: 10.5px; color: var(--muted-2); }
|
||||
.f-hint { font-size: 11px; color: var(--muted-2); line-height: 1.6; margin: var(--gap-xs) 0 0 88px; }
|
||||
.f-row-note { font-size: 11.5px; color: var(--muted); line-height: 1.6; margin-top: var(--gap-s); }
|
||||
.row-actions { display: flex; align-items: center; gap: var(--gap-sm); margin-top: var(--gap); }
|
||||
.test-res { font-size: 11.5px; color: var(--ok); }
|
||||
.test-res.bad { color: var(--err); }
|
||||
.shared-note { font-size: 12px; color: var(--muted); background: var(--chip); padding: 8px 10px; border-radius: var(--radius-s); margin-bottom: var(--gap-s); }
|
||||
.ops-row { display: flex; gap: 7px; margin-top: 12px; }
|
||||
@media (max-width: 768px) {
|
||||
.ag-layout { grid-template-columns: 1fr; }
|
||||
.chat-layout { grid-template-columns: 1fr; height: auto; }
|
||||
.chat-side { display: none; }
|
||||
.cfg-grid { grid-template-columns: 1fr; }
|
||||
.cfg-grid > .card:first-child { grid-column: auto; }
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user