Commit Graph

16 Commits

Author SHA1 Message Date
hailin 12e622040a fix(admin): add Markdown rendering to System Supervisor chat
Supervisor responses contain rich Markdown (tables, headers, bold,
lists, code). Previously rendered as plain text with pre-wrap.

- Install react-markdown + remark-gfm for GFM table support
- Wrap assistant messages in ReactMarkdown component
- Add .supervisor-markdown CSS styles (tables, headings, lists, hr, code)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 21:01:20 -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 bb1a1139a3 feat(agents): add 4-layer response quality control — structured outputs, LLM judge, smart truncation
AI回复质量硬约束系统,解决核心问题:AI无法用最少的语言精准回答用户问题。

## 四层防线架构

### Layer 1 — Prompt 优化 (软约束)
- coordinator-system-prompt.ts: 新增"最高优先级原则:精准回答"章节
  - 意图分类表(7种)+ 每种对应长度和回答策略
  - 错误示范 vs 正确示范对比
  - "宁可太短,不可太长"原则
  - 最终提醒三条:精准回答 > 准确性 > 简洁就是专业
- policy-expert-prompt.ts: 精简输出格式
- objection-handler-prompt.ts: 微调

### Layer 2 — Structured Outputs (格式约束)
- 新文件 coordinator-response.schema.ts: Zod schema 定义
  - intent: 7种意图分类 (factual/yes_no/comparison/assessment/objection/detailed/casual)
  - answer: 回复文本
  - followUp: 可选跟进问题
- agent-loop.ts: 通过 output_config 传入 Claude API,强制 JSON 输出
  - 流式模式下抑制 text delta(JSON 片段不展示给用户)
  - 流结束后解析 JSON,提取 answer 字段 yield 给前端
  - JSON 解析失败时回退到原始文本(安全降级)
- coordinator-agent.service.ts: 传入 zodOutputFormat(CoordinatorResponseSchema)
- agent.types.ts: AgentLoopParams 新增 outputConfig 字段

### Layer 3 — LLM-as-Judge (语义质检)
- evaluation-rule.entity.ts: 新增 LLM_JUDGE 规则类型(第9种)
- evaluation-gate.service.ts:
  - 注入 ConfigService + 初始化 Anthropic client (Haiku 4.5)
  - evaluateRule 改为 async(支持异步 LLM 调用)
  - 新增 checkLlmJudge():评估 relevance/conciseness/noise 三维度
  - 可配置阈值:minRelevance(7), minConciseness(6), maxNoise(3)
  - 5s 超时 + 异常默认通过(非阻塞)
  - EvaluationContext 新增 userMessage 字段
- coordinator-agent.service.ts: 传入 userMessage 到评估门控

### Layer 4 — 程序级硬截断 (物理约束)
- coordinator-response.schema.ts:
  - INTENT_MAX_ANSWER_LENGTH: 按意图限制字符数
    factual=200, yes_no=120, comparison=250, assessment=400,
    objection=200, detailed=500, casual=80
  - MAX_FOLLOWUP_LENGTH: 80 字符
  - smartTruncate(): 在句子边界处智能截断(中英文标点)
- agent-loop.ts: JSON 解析后按 intent 强制截断 answer 和 followUp
- max_tokens 从 4096 降至 2048

## Bug 修复
- agent-loop.ts: currentTextContent 在 content_block_stop 时被重置为空字符串,
  导致评估门控收到空文本。改为从 finalMessage.content 提取 responseText。

## 依赖升级
- @anthropic-ai/sdk: 0.52.0 → 0.73.0 (支持 output_config)
- 新增 zod@4.3.6 (Structured Output schema 定义)

## 文件清单 (1 new + 10 modified)
- NEW: agents/schemas/coordinator-response.schema.ts
- MOD: agents/coordinator/agent-loop.ts (核心改造)
- MOD: agents/coordinator/coordinator-agent.service.ts
- MOD: agents/coordinator/evaluation-gate.service.ts
- MOD: agents/types/agent.types.ts
- MOD: agents/prompts/coordinator-system-prompt.ts
- MOD: agents/prompts/policy-expert-prompt.ts
- MOD: agents/prompts/objection-handler-prompt.ts
- MOD: domain/entities/evaluation-rule.entity.ts
- MOD: package.json + pnpm-lock.yaml

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 01:01:05 -08:00
hailin e16ec7930d feat(knowledge): add file upload with text extraction for knowledge base
支持在管理后台知识库页面上传文件(PDF、Word、TXT、Markdown),
自动提取文本内容,管理员预览编辑后保存为知识库文章。

## 后端 (knowledge-service)

- 新增 TextExtractionService:文件文本提取服务
  - PDF 提取:使用 pdf-parse v2 (PDFParse class API)
  - Word (.docx) 提取:使用 mammoth.extractRawText()
  - TXT/Markdown:直接 UTF-8 解码
  - 支持中英文混合字数统计
  - 文件大小限制 200MB,类型校验(MIME 白名单)
  - 空文本 PDF(扫描件/图片)返回友好错误提示

- 新增上传接口:POST /knowledge/articles/upload
  - 使用 NestJS FileInterceptor 处理 multipart/form-data
  - 仅提取文本并返回,不直接创建文章(两步流程)
  - 返回:extractedText, suggestedTitle, wordCount, pageCount

- 新增 ExtractedTextResponse DTO
- KnowledgeModule 注册 TextExtractionService

## 前端 (admin-client)

- knowledge.api.ts:新增 uploadFile() 方法(FormData + 120s 超时)
- useKnowledge.ts:新增 useUploadKnowledgeFile hook
- KnowledgePage.tsx:
  - 新增 Segmented 切换器(手动输入 / 文件上传),仅新建时显示
  - 文件上传模式显示 Upload.Dragger 拖拽上传区域
  - 上传后自动提取文本,填入标题+内容字段
  - 提取完成自动切回手动模式,管理员可预览编辑后保存
  - 显示提取结果(字数、页数)

## 用户流程

新建文章 → 切换"文件上传" → 拖入/选择文件 → 系统提取文本
→ 自动填入标题+内容 → 管理员编辑确认 → 点击保存

## 依赖

- pdf-parse@^2.4.5(PDF 文本提取)
- mammoth@^1.8.0(Word 文档文本提取)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 22:58:19 -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 1df5854825 feat(multi-tenant): apply tenant middleware and refactor repositories
- Apply TenantContextMiddleware to all 6 services
- Add SimpleTenantFinder for services without direct tenant DB access
- Add TenantFinderService for evolution-service with database access
- Refactor 8 repositories to extend BaseTenantRepository:
  - user-postgres.repository.ts
  - verification-code-postgres.repository.ts
  - conversation-postgres.repository.ts
  - message-postgres.repository.ts
  - token-usage-postgres.repository.ts
  - file-postgres.repository.ts
  - order-postgres.repository.ts
  - payment-postgres.repository.ts
- Add @iconsulting/shared dependency to evolution-service and knowledge-service
- Configure middleware to exclude health and super-admin paths

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 18:30:31 -08:00
hailin 422069be68 feat: add enterprise multi-tenancy infrastructure
- Add shared tenant module with AsyncLocalStorage-based context management
- Create TenantContextService, TenantContextMiddleware, TenantGuard
- Add @TenantId(), @Tenant(), @RequireFeatures() decorators
- Create BaseTenantRepository for automatic tenant filtering
- Add TenantORM entity for tenants table
- Add tenant_id column to all 16 ORM entities across 6 services
- Create database migration script for multi-tenancy support
- Add tenant-related error codes

This implements row-level isolation for 100% data separation between tenants.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 18:11:12 -08:00
hailin 931055b51f feat(admin): add conversation management with device tracking display
## Backend (conversation-service)
- Add AdminConversationController with JWT auth for admin API
- Endpoints: list conversations, by user, detail, messages, statistics
- Support filtering by status, userId, date range, conversion
- Add JWT_SECRET environment variable to docker-compose.yml
- Add jsonwebtoken dependency for admin token verification

## Frontend (admin-client)
### New Features:
- Add conversations feature module with:
  - API layer (conversations.api.ts)
  - React Query hooks (useConversations.ts)
  - ConversationsPage with full management UI

### User Management Enhancement:
- Add "最近咨询记录" section in user detail drawer
- Display device info for each conversation:
  - IP address with region
  - User-Agent (parsed to browser/OS)
  - Device fingerprint
- Show conversation status, conversion status, message count

### Navigation:
- Add "对话管理" menu item with MessageOutlined icon
- Add /conversations route

## Files Added:
- admin-conversation.controller.ts (backend admin API)
- conversations feature folder (frontend)
  - infrastructure/conversations.api.ts
  - application/useConversations.ts
  - presentation/pages/ConversationsPage.tsx

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 10:04:17 -08:00
hailin 28df6fb89c chore: update pnpm-lock.yaml for jsonwebtoken dependency
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 09:05:57 -08:00
hailin 042d2e1456 feat(analytics): implement statistics, financial reports, and audit logging
Backend (evolution-service):
- Add analytics module with scheduled statistics aggregation
- Implement daily_statistics aggregation (OVERALL, CHANNEL, CATEGORY)
- Add monthly financial report generation and management
- Create audit log service for operation tracking
- Schedule cron jobs for automatic data aggregation

Frontend (admin-client):
- Replace dashboard mock data with real API calls
- Add analytics page with trend charts and dimension breakdown
- Add financial reports page with confirm/lock workflow
- Add audit logs page with filtering and detail view
- Update navigation with analytics submenu

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 08:01:39 -08:00
hailin 02954f56db refactor(services): implement Clean Architecture across 4 services
## Overview
Refactor user-service, payment-service, file-service, and conversation-service
to follow Clean Architecture pattern based on knowledge-service reference.

## Architecture Pattern Applied

```
src/
├── domain/
│   ├── entities/           # Pure domain entities (no ORM decorators)
│   └── repositories/       # Repository interfaces + Symbol DI tokens
├── infrastructure/
│   └── database/postgres/
│       ├── entities/       # ORM entities with TypeORM decorators
│       └── *-postgres.repository.ts  # Repository implementations
└── {feature}/
    └── {feature}.module.ts # DI configuration with Symbol providers
```

## Changes by Service

### user-service (40% → 100% compliant)
- Created: IUserRepository, IVerificationCodeRepository interfaces
- Created: UserORM, VerificationCodeORM entities
- Created: UserPostgresRepository, VerificationCodePostgresRepository
- Modified: UserEntity, VerificationCodeEntity → pure domain with factory methods
- Updated: user.module.ts, auth.module.ts with Symbol-based DI

### payment-service (50% → 100% compliant)
- Created: IOrderRepository, IPaymentRepository interfaces
- Created: OrderORM, PaymentORM entities
- Created: OrderPostgresRepository, PaymentPostgresRepository
- Modified: OrderEntity, PaymentEntity → pure domain with factory methods
- Updated: order.module.ts, payment.module.ts with Symbol-based DI

### file-service (40% → 100% compliant)
- Created: IFileRepository interface
- Created: FileORM entity
- Created: FilePostgresRepository
- Modified: FileEntity → pure domain with factory methods
- Updated: file.module.ts with Symbol-based DI

### conversation-service (60% → 100% compliant)
- Created: IConversationRepository, IMessageRepository, ITokenUsageRepository
- Created: ConversationORM, MessageORM, TokenUsageORM entities
- Created: ConversationPostgresRepository, MessagePostgresRepository,
          TokenUsagePostgresRepository
- Modified: ConversationEntity, MessageEntity, TokenUsageEntity → pure domain
- Updated: conversation.module.ts with Symbol-based DI
- Updated: app.module.ts, data-source.ts entity patterns

## Key Implementation Details

1. **Symbol-based DI Pattern**:
   ```typescript
   export const USER_REPOSITORY = Symbol('IUserRepository');

   @Module({
     providers: [{ provide: USER_REPOSITORY, useClass: UserPostgresRepository }],
     exports: [UserService, USER_REPOSITORY],
   })
   ```

2. **Pure Domain Entities**: Factory methods `create()` and `fromPersistence()`
   for controlled instantiation without ORM decorators

3. **Repository Implementations**: Include `toORM()` and `toEntity()` conversion
   methods for anti-corruption layer between domain and infrastructure

4. **Entity Discovery**: Changed glob pattern from `*.entity` to `*.orm`
   in app.module.ts and data-source.ts files

## Breaking Changes
- None for API consumers
- Internal architecture restructuring only

## Testing
- All 4 services compile successfully with `pnpm build`
- Database schema compatibility verified (column mappings preserved)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-24 21:18:25 -08:00
hailin d4925719fc feat(multimodal): add file upload and image support for chat
- Add MinIO object storage to docker-compose infrastructure
- Create file-service microservice for upload management with presigned URLs
- Add files table to database schema
- Update nginx and Kong for MinIO proxy routes
- Implement file upload UI in chat InputArea with drag-and-drop
- Add attachment preview in MessageBubble component
- Update conversation-service to handle multimodal messages
- Add Claude Vision API integration for image analysis

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 05:34:41 -08:00
hailin c914693f94 feat(web): add markdown rendering for AI responses 2026-01-10 01:33:00 -08:00
hailin 7f2fc153b5 refactor: simplify Anthropic client config using baseURL
Remove https-proxy-agent dependency since ANTHROPIC_BASE_URL already
supports pointing to a proxy server directly.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 20:45:44 -08:00
hailin ea760b5695 chore: update pnpm-lock.yaml for https-proxy-agent
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 20:37:36 -08:00
hailin a7add8ff90 Initial commit: iConsulting 香港移民咨询智能客服系统
项目架构:
- Monorepo (pnpm + Turborepo)
- 后端: NestJS 微服务 + Claude Agent SDK
- 前端: React + Vite + Ant Design

包含服务:
- conversation-service: 对话服务 (Claude AI)
- user-service: 用户认证服务
- payment-service: 支付服务 (支付宝/微信/Stripe)
- knowledge-service: 知识库服务 (RAG + Neo4j)
- evolution-service: 自我进化服务
- web-client: 用户前端
- admin-client: 管理后台

基础设施:
- PostgreSQL + Redis + Neo4j
- Kong API Gateway
- Nginx 反向代理
- Docker Compose 部署配置

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 00:01:12 -08:00