hailin
5034ef4a70
feat(admin): add System Supervisor — global system status chat interface
...
Add a "系统总监" (System Supervisor) feature that provides admins with
a natural language chat interface to query the entire iConsulting system's
operational status, including all 7 specialist agents, directives, token
usage, conversation statistics, and system health.
Backend:
- SystemSupervisorChatService: Haiku 4.5 with 7 read-only tools
- get_agent_configs: list all 7 agent model/parameter configs
- get_agent_execution_stats: execution counts, success rates, latency
- get_directives_summary: assessment + collection directive overview
- get_token_usage_stats: token consumption and cost by model
- get_conversation_stats: conversation counts, conversion rates, stages
- get_evaluation_rules: quality gate rule configuration
- get_system_health: circuit breakers, Redis, service availability
- AdminSupervisorController: POST /conversations/admin/supervisor/chat
- Registered in AgentsModule (provider + export) and ConversationModule
- Added AgentExecutionORM to TypeOrmModule.forFeature in AgentsModule
Frontend (admin-client):
- features/supervisor/ with Clean Architecture layers:
- infrastructure/supervisor.api.ts: HTTP client
- application/useSupervisor.ts: React Query mutation hook
- presentation/pages/SupervisorPage.tsx: full-page chat UI
- Quick action buttons: 系统概况, Agent统计, 成本报告, 健康检查
- Route: /supervisor, menu icon: EyeOutlined (between 收集指令 and 数据分析)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 20:49:57 -08:00
hailin
8e4bd95dda
feat(agents): add Collection Expert specialist + admin directive system
...
## Part A: Collection Expert Specialist Agent (7th specialist)
- New specialist: CollectionExpertService (Haiku 4.5, maxTurns 2)
- Analyzes user info completeness against 12-item weighted checklist
- Identifies missing fields, recommends next questions
- Category-specific priority adjustments (QMAS/GEP/IANG/TTPS/CIES/TechTAS)
- Tools: search_knowledge, get_user_context
- Admin directive injection: loads active directives from DB before each run
- Prompt: collection-expert-prompt.ts (completeness calc, validation rules, JSON output)
- Coordinator integration: invoke_collection_expert tool + case in executeAgentTool
- System prompt: section 2.6 usage guide, section 4.3 optional invocation reference
## Part B: Admin Directive System (parallel to assessment directives)
- ORM: CollectionDirectiveORM (collection_directives table)
- Types: general, priority, category, validation
- Multi-tenant with tenant_id + enabled indexes
- SQL: CREATE TABLE collection_directives in init-db.sql
- Controller: /conversations/admin/collection-directives (10 REST endpoints)
- CRUD + toggle + reset + preview + AI chat
- Chat Service: CollectionDirectiveChatService (Haiku 4.5 tool loop)
- 5 tools: list/create/update/delete/reset directives
- mutated flag for frontend cache invalidation
## Part C: Frontend Admin-Client
- Feature module: features/collection-config/ (5 files)
- API client, React Query hooks, Config page, Chat drawer
- Directive types: 通用指令/优先级调整/类别配置/验证规则
- Route: /collection-config in App.tsx
- Sidebar: FormOutlined icon, label '收集指令' in MainLayout.tsx
Files: 11 new, 9 modified | Backend + frontend compile clean
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 20:07:33 -08:00
hailin
22bca31690
feat(agents): add AI chat interface for directive management
...
Add a conversational chat drawer to the assessment config admin page,
allowing admins to manage assessment directives via natural language.
Backend:
- DirectiveChatService: Haiku 4.5 LLM with 5 tools (list, create,
update, delete, reset) and iterative tool loop (max 5 turns)
- System prompt dynamically includes current directive state from DB
- POST /chat endpoint on admin-assessment-directive controller
- Registered in AgentsModule (global), injected via @Optional()
Frontend:
- DirectiveChatDrawer: Ant Design Drawer (480px) with message list,
input box (Enter to send, Shift+Enter for newline), loading state
- useDirectiveChat hook: React Query mutation, auto-invalidates
directive queries when response.mutated === true
- "AI 助手" button added to AssessmentConfigPage header
Files:
- NEW: agents/admin/directive-chat.service.ts (LLM tool-loop service)
- NEW: components/DirectiveChatDrawer.tsx (chat drawer UI)
- MOD: agents.module.ts (register + export DirectiveChatService)
- MOD: admin-assessment-directive.controller.ts (POST /chat endpoint)
- MOD: assessment-config.api.ts (chat API method + types)
- MOD: useAssessmentConfig.ts (useDirectiveChat hook)
- MOD: AssessmentConfigPage.tsx (AI button + drawer integration)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 19:17:07 -08:00
hailin
9feb03153b
feat(agents): add admin assessment directive system for dynamic prompt injection
...
Admins can now write natural-language directives that get injected into the
assessment expert's system prompt. Directives are stored in DB, loaded per
execution, and support incremental additions, toggling, and full reset.
Backend:
- New assessment_directives table + ORM entity
- Admin CRUD API at /conversations/admin/assessment-directives
- buildAssessmentExpertPrompt() accepts optional adminDirectives param
- AssessmentExpertService loads active directives from DB before each execution
- Fail-safe: missing repo/tenant context → default prompt (no directives)
Frontend (admin-client):
- New "评估指令" page with table, create/edit modals, toggle switches
- Prompt preview panel showing assembled directive text
- Reset-to-default with confirmation
- React Query hooks for all CRUD operations
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 18:21:21 -08:00
hailin
95f36752c9
feat(agents): add prompt-driven execution tools with DB persistence
...
Add 4 new tools (generate_document, manage_checklist, create_timeline,
query_user_artifacts) enabling the agent to create and manage persistent
user artifacts. Artifacts are saved to PostgreSQL and support dedup by
title, update-in-place, and cross-session querying. Frontend renders
rich UI cards for each artifact type.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 07:35:08 -08:00
hailin
0d488ac68b
feat(agents): add Redis checkpoint for agent loop crash recovery
...
- New RedisClientService: optional ioredis wrapper, gracefully degrades without REDIS_URL
- New RedisModule: global NestJS module providing Redis connectivity
- AgentCheckpoint interface: captures turn, messages, cost, agents, timestamp
- Agent loop saves checkpoint after each tool execution batch (TTL=10min)
- On restart with same conversationId+requestId, loads checkpoint and resumes from saved state
- Checkpoint auto-deleted after load to prevent stale recovery
- Coordinator injects @Optional() RedisClientService, builds save/load callbacks
- Zero impact when Redis is not configured — checkpoint silently skipped
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 04:27:25 -08:00
hailin
198ff4b349
feat(agents): add PreToolUse/PostToolUse hook system for tool call interception
...
- New ToolHooksService with dynamic hook registration (pre/post)
- Built-in audit logging: tool name, type, user, duration, success/failure
- Fail-open design: individual hook failures don't block tool execution
- Integrated into coordinator's createToolExecutor with full context
- Hook context includes: toolName, toolType (agent/direct/mcp), traceId, timing
- Supports future extensions: rate limiting, permission checks, analytics
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 04:09:14 -08:00
hailin
43d4102e1f
feat(agents): add query_user_profile tool for user info lookup
...
新增 query_user_profile 工具,让 AI agent 能回答用户关于自身信息的查询,
例如"这是我第几次咨询?"、"你记得我的信息吗?"、"我之前咨询过什么?"
## 问题背景
当用户问"这是我第几次跟你咨询?"时,AI 无法回答,因为没有任何工具
能查询用户的历史咨询数据。
## 实现方案:双层设计
### 第一层:被动上下文注入(Context Injector)
- context-injector.service.ts 注入 ConversationORM repo + TenantContextService
- buildConversationStatsBlock() 现在自动查询用户累计咨询次数
- 每次对话自动注入 `用户累计咨询次数: N 次(含本次对话)`
- 简单问题("这是第几次?")AI 可直接从上下文回答,零工具调用
### 第二层:主动工具调用(query_user_profile)
用户需要详细信息时,AI 调用此工具,返回完整档案:
- 咨询统计:累计次数、首次/最近咨询时间、类别分布
- 最近对话:最近 10 个对话的标题、类别、阶段
- 用户画像:系统记忆中的事实(学历/年龄/职业)、偏好、意图
- 订单统计:总单数、已支付、待支付
## 修改文件
- agents.module.ts: 添加 ConversationORM 到 TypeORM imports
- coordinator-tools.ts: 新增 query_user_profile 工具定义(只读)
- immigration-tools.service.ts: 注入 ConversationORM repo + TenantContextService,
实现 queryUserProfile() 方法(并行查询对话+记忆+订单)
- coordinator-system-prompt.ts: 第3.3节添加工具文档和使用指引
- context-injector.service.ts: 注入 repo,conversation_stats 块添加累计咨询次数
## 依赖关系
- 无循环依赖:直接使用 TypeORM Repository<ConversationORM>(数据访问层),
不依赖 ConversationService(避免 AgentsModule ↔ ConversationModule 循环)
- TenantContextService 全局可用,确保多租户隔离
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 12:17:23 -08:00
hailin
df754ce8b8
feat(payment): P0 — 支付闭环,Agent 可创建真实订单并生成支付二维码
...
## 后端改动
### 新增 PaymentClientService
- 新建 `infrastructure/payment/payment-client.service.ts`
- HTTP 客户端封装,调用 payment-service API(端口 3002)
- 方法: createOrder, createPayment, checkPaymentStatus, getOrderStatus, getUserOrders
- 基于 native fetch,模式与 KnowledgeClientService 一致
- 新建 `infrastructure/payment/payment.module.ts`
- AgentsModule 导入 PaymentModule
### 重写 generate_payment 工具
- 删除所有 MOCK 数据(fake orderId, placeholder QR URL)
- 实际调用 payment-service: createOrder → createPayment → 返回真实 QR URL
- 返回 orderId, paymentId, qrCodeUrl, paymentUrl, expiresAt
### 新增 check_payment_status 工具
- 查询订单支付状态(调用 payment-service GET /orders/:id/status)
- 返回 status, statusLabel(中文映射), paidAt
- 在 coordinator-tools.ts 和 concurrency map 中注册(只读 safe=true)
### 新增 query_order_history 工具
- 查询用户历史订单列表(调用 payment-service GET /orders)
- 返回 orders 数组含 orderId, serviceType, amount, status, createdAt
- 在 coordinator-tools.ts 和 concurrency map 中注册(只读 safe=true)
## 前端改动
### QR 码渲染
- 安装 qrcode.react 4.2.0
- ToolCallResult 组件使用 QRCodeSVG 渲染真实二维码
- 支持 qrCodeUrl(二维码)和 paymentUrl(跳转链接)两种支付方式
- 显示订单号、金额、过期时间
### 支付状态卡片
- check_payment_status 结果渲染为彩色状态卡片
- 已支付=绿色, 待支付=黄色, 已取消=红色, 已退款=橙色
### 订单历史列表
- query_order_history 结果渲染为订单列表卡片
- 每行显示: 类别、日期、金额、状态标签
### WebSocket 工具事件处理
- tool_result 事件收集到 pendingToolResults(chatStore 新增状态)
- stream_end 时将 toolResults 注入消息 metadata.toolCalls
- stream_start 时清空 pendingToolResults
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 01:17:14 -08:00
hailin
04dbc61131
feat(agents): add capability boundary guardrails — input gate, cascading fallback, output gate rules
...
Four guardrail improvements to enforce agent capability boundaries:
1. Cascading Fallback (Fix 1+4):
- Rewrite searchKnowledge() in immigration-tools.service.ts with 3-tier fallback:
KB (similarity >= 0.55) → Web Search → Built-in Knowledge (clearly labeled)
- Rewrite executeTool() in policy-expert.service.ts to use retrieveKnowledge()
with confidence threshold; returns [KB_EMPTY]/[KB_LOW_CONFIDENCE]/[KB_ERROR]
markers so the model knows to label source reliability
2. Input Gate (Fix 2):
- New InputGateService using Haiku for lightweight pre-classification
- Classifications: ON_TOPIC / OFF_TOPIC (threshold >= 0.7) / HARMFUL (>= 0.6)
- Short messages (< 5 chars) fast-path to ON_TOPIC
- Gate failure is non-fatal (allows message through)
- Integrated in CoordinatorAgentService.sendMessage() before agent loop entry
- OFF_TOPIC/HARMFUL messages get fixed responses without entering agent loop
3. Output Gate Enhancement (Fix 3):
- Add TOPIC_BOUNDARY and NO_FABRICATION to EvaluationRuleType
- TOPIC_BOUNDARY: regex detection for code blocks, programming keywords,
AI identity exposure, off-topic indicators in agent responses
- NO_FABRICATION: detects policy claims without policy_expert invocation
or source markers; ensures factual claims are knowledge-backed
- Both rule types are admin-configurable (zero rules = zero checks)
- No DB migration needed (ruleType is varchar(50))
Files changed:
- NEW: agents/coordinator/input-gate.service.ts
- MOD: agents/coordinator/coordinator-agent.service.ts (inject InputGate + gate check)
- MOD: agents/agents.module.ts (register InputGateService)
- MOD: agents/coordinator/evaluation-gate.service.ts (2 new evaluators)
- MOD: domain/entities/evaluation-rule.entity.ts (2 new rule types)
- MOD: agents/specialists/policy-expert.service.ts (RAG confidence threshold)
- MOD: claude/tools/immigration-tools.service.ts (cascading fallback)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 21:59:10 -08:00
hailin
51a7589fbf
fix(agents): export EVALUATION_RULE_REPOSITORY from AgentsModule
...
The AdminEvaluationRuleController in ConversationModule needs the
EVALUATION_RULE_REPOSITORY token. Even though AgentsModule is @Global(),
Symbol-based providers must be explicitly exported to be available
in other modules.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 19:45:38 -08:00
hailin
00a0ac3820
feat(agents): add admin-configurable evaluation gate for agent loop quality control
...
Add a configurable evaluation gate system that allows administrators to
define quality rules per consulting stage. The gate checks are executed
programmatically before the agent loop returns a response to the user.
## Architecture
- **Zero-config safe**: Empty rules table = no checks = current behavior preserved
- **Callback-based decoupling**: agent-loop.ts receives an optional callback,
stays decoupled from database layer
- **Max 1 retry**: On RETRY/SUPPLEMENT failure, recurse once without gate to
prevent infinite loops
- **Error-tolerant**: Gate exceptions are caught and logged, never block responses
## New files
- `database/migrations/20260206_add_evaluation_rules.sql` — DB migration
- `domain/entities/evaluation-rule.entity.ts` — Domain entity with 6 rule types
(FIELD_COMPLETENESS, ASSESSMENT_QUALITY, RESPONSE_LENGTH, MUST_CONTAIN,
STAGE_MIN_TURNS, CONVERSION_SIGNAL) and 4 failure actions (RETRY, SUPPLEMENT,
WARN_AND_PASS, ESCALATE)
- `domain/repositories/evaluation-rule.repository.interface.ts` — Repository contract
- `infrastructure/database/postgres/entities/evaluation-rule.orm.ts` — TypeORM ORM entity
- `infrastructure/database/postgres/repositories/evaluation-rule.repository.ts` — Repository impl
- `infrastructure/agents/coordinator/evaluation-gate.service.ts` — Core evaluation engine
with 5-minute rule cache, per-rule-type evaluators, severity-based action resolution,
and feedback message builder for model retry
- `application/dtos/evaluation-rule.dto.ts` — Create/Update/Test DTOs
- `adapters/inbound/admin-evaluation-rule.controller.ts` — Admin CRUD API with 8 endpoints:
list, get, create, update, delete, toggle, test (dry-run), clear cache
## Modified files
- `agent.types.ts` — Add optional `evaluationGate` callback to `AgentLoopParams`
- `stream.types.ts` — Add `EvaluationWarningEvent`, `'evaluating'` phase
- `agent-loop.ts` — Insert gate check at termination point (line 315)
- `coordinator-agent.service.ts` — Inject EvaluationGateService, build callback,
handle `evaluation_warning` event in StreamChunk mapping
- `agents.module.ts` — Register EvaluationRuleORM, repository, EvaluationGateService
- `conversation.module.ts` — Register AdminEvaluationRuleController
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 18:56:52 -08:00
hailin
714a674818
feat(mcp): add MCP Server management — backend API + admin UI
...
实现完整的 MCP (Model Context Protocol) 服务器管理功能,包括后端 API 和管理界面。
## 后端 (conversation-service)
### MCP 混合架构核心 (新增)
- mcp.types.ts: MCP 类型定义 (McpServerConfig, McpToolDefinition, McpConnectionState 等)
- mcp-config.service.ts: 配置解析 — 支持环境变量 MCP_SERVERS 和租户级配置
- mcp-client.service.ts: MCP 客户端 — 连接管理、工具发现、工具执行、运行时增删改
- mcp.module.ts: @Global NestJS 模块,注册 MCP 服务 + TypeORM 实体 + Repository
### 数据持久化 (新增)
- 20260206_add_mcp_server_configs.sql: 数据库迁移 — mcp_server_configs 表
- mcp-server-config.orm.ts: TypeORM 实体 (tenant_id 支持多租户)
- mcp-server-config.repository.ts: Repository 层 (CRUD + ORM→McpServerConfig 转换)
### Admin API (新增)
- admin-mcp.controller.ts: 11 个管理端点,路由前缀 conversations/admin/mcp
- GET /overview — 统计信息 (服务器总数、已连接、错误、工具总数)
- GET/POST /servers — 列表 + 创建
- GET/PUT/DELETE /servers/:id — 详情 + 更新 + 删除
- POST /servers/:id/connect — 手动连接
- POST /servers/:id/disconnect — 手动断开
- GET /servers/:id/tools — 查看已发现工具
- POST /servers/:id/test — 测试连接
- POST /test-config — 测试未保存的配置
### 已有文件修改
- coordinator-tools.ts: getToolsForClaudeAPI() 支持 additionalTools 可选参数
- agent-loop.ts: 支持 additionalTools + additionalConcurrencyMap 透传
- coordinator-agent.service.ts: 注入 McpClientService,工具路由加 MCP 分支
- agents.module.ts: 导入 McpModule
- conversation.module.ts: 注册 AdminMcpController
## 前端 (admin-client)
### API + Hooks (新增)
- mcp.api.ts: Axios API 客户端 + 完整 TypeScript 类型定义
- useMcp.ts: 10 个 React Query hooks (queries + mutations)
### UI 页面 (新增)
- McpPage.tsx: 主页面 — 统计卡片 + 服务器表格 + 操作按钮
- ServerFormDrawer.tsx: 创建/编辑表单 — 基本信息、传输配置、高级设置、连接测试
- ServerDetailDrawer.tsx: 详情抽屉 — 配置展示、工具浏览 (Collapse + JSON Schema)
### 路由 + 导航
- App.tsx: 添加 /mcp 路由
- MainLayout.tsx: 侧边栏添加 "MCP 服务器" 菜单项 (ApiOutlined 图标)
## 依赖
- @modelcontextprotocol/sdk: ^1.0.0 (MCP 协议 SDK)
## 架构设计
- 混合架构: 16 个内置工具保持不变 + MCP 工具动态发现/热插拔
- 工具名前缀 mcp__{serverId}__{toolName} 确保零冲突
- 优雅降级: MCP 连接失败不影响内置工具,仅 log 记录
- 启动加载: 先连接环境变量配置,再连接数据库配置
- 运行时管理: 支持不重启服务即可增删改 MCP Server
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 18:29:02 -08:00
hailin
16cc0e4c08
feat(agents): implement multi-agent collaboration architecture
...
借鉴 Claude Code 的架构模式,将单一 Agent 重构为 Coordinator + 6 Specialist 多 Agent 协作系统。
## 新增文件 (36个)
### 架构设计文档 (docs/architecture/, 12个)
- 00-overview.md ~ 11-prompt-templates.md: 完整架构设计,覆盖所有 Agent 的详细设计、
Prompt 模板、协作流程、工具并发系统、动态上下文注入
### 多 Agent 系统 (infrastructure/agents/, 23个)
- coordinator/coordinator-agent.service.ts: 主协调器,替代 ClaudeAgentServiceV2
- coordinator/agent-loop.ts: 核心递归 async generator 循环(参考 Claude Code aM())
- coordinator/context-injector.service.ts: 动态上下文注入(8种上下文类型按优先级注入)
- specialists/base-specialist.service.ts: Agent 基类(封装 Claude API 调用 + prompt 缓存)
- specialists/policy-expert.service.ts: 政策专家 (Sonnet 4, temp=0)
- specialists/assessment-expert.service.ts: 评估专家 (Sonnet 4, temp=0)
- specialists/strategist.service.ts: 策略顾问 (Sonnet 4, temp=0.3)
- specialists/objection-handler.service.ts: 异议处理 (Sonnet 4, temp=0.2)
- specialists/case-analyst.service.ts: 案例分析 (Haiku, temp=0)
- specialists/memory-manager.service.ts: 记忆管理 (Haiku, temp=0)
- prompts/coordinator-system-prompt.ts: 协调器 Prompt(1095行,13章)
- prompts/{policy,assessment,strategist,objection,case,memory}-*-prompt.ts: 各专家 Prompt
- tools/coordinator-tools.ts: 16个工具定义(6 Agent 调用 + 10 直接工具)
- tools/tool-execution-queue.ts: 并发执行队列(isConcurrencySafe 控制并行/串行)
- types/agent.types.ts: Agent 配置、输入/输出类型定义
- types/stream.types.ts: 流式事件类型(含 agent_start/complete/coordinator_thinking)
- types/context.types.ts: 上下文注入类型
- agents.module.ts: NestJS 模块注册
### 前端 Agent 状态展示 (1个)
- AgentStatusIndicator.tsx: 多 Agent 工作状态组件(含动画)
## 修改文件 (15个)
### 后端集成
- conversation.service.ts: 切换到 CoordinatorAgentService
- conversation.gateway.ts: 新增 agent_start/agent_complete/coordinator_thinking 事件
- claude.module.ts: 引入 AgentsModule
- agents.module.ts: 注册 ImmigrationToolsService(复用旧版生产测试的工具实现)
- knowledge-client.service.ts: 新增 search()/getUserContext() 便捷方法
### 旧代码标记 @deprecated
- claude-agent.service.ts, claude-agent-v2.service.ts
- strategy-engine.service.ts, intent-classifier.ts, response-gate.ts
### 前端适配
- chatStore.ts: 新增 ActiveAgent/CompletedAgent/CoordinatorPhase 状态
- useChat.ts: 新增 WebSocket 事件处理
- ChatWindow.tsx: 集成 AgentStatusIndicator
- globals.css: 新增 agentPulse/agentSlideIn 动画
### 共享类型
- conversation.types.ts: 新增 AGENT_START/AGENT_COMPLETE/COORDINATOR_THINKING 事件
## 核心设计决策
1. **新旧结合**: Coordinator 的 10 个直接工具委托给旧版 ImmigrationToolsService
(经过生产测试的 Google Search、汇率 API、新闻 API 等),6 个 Agent 调用工具
走新的 Specialist Agent 系统
2. **递归 async generator**: agent-loop 支持流式输出 + 工具递归 + 成本/轮次控制
3. **并行 Agent 执行**: ToolExecutionQueue 根据 isConcurrencySafe 自动并行/串行
4. **Prompt 缓存**: 所有 Agent 的 system prompt 使用 cache_control: ephemeral
5. **速率限制重试**: 429/529 指数退避,最多 2 次
6. **向后兼容**: LegacyConversationContext 类型别名,StreamChunk 扩展不破坏现有结构
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 04:26:39 -08:00