Quay lai

Tai lieu ky thuat

Tai lieu ky thuat - BA Agent System

Kien truc, cau hinh, API va huong dan van hanh he thong

Kien truc he thong

BA Agent System su dung kien truc Multi-Agent, trong do moi agent chuyen xu ly mot giai doan cua quy trinh BA.

High-level Architecture

Browser (index.html)
    |
    v
Express Server (server.js) ---- Confluence DC (REST API)
    |
    v
AI Service (AIService.js) ---- Claude API (Anthropic SDK)
    |
    v
Session Manager (SessionManager.js) ---- JSON File Storage
    |
    v
Multi-Agent System
  ├── DiscoveryAgent      - Thu thap yeu cau
  ├── AnalysisAgent       - Phan tich va phan loai
  ├── DocumentationAgent  - Tao tai lieu (BRD, URD)
  ├── UseCaseAgent        - Tao Use Cases
  ├── VisualizationAgent  - Tao Diagrams
  ├── ValidationAgent     - Kiem tra chat luong
  └── PublishAgent        - Tong hop va xuat ban

Document Generation Flow

BRD (Input)
Discovery Q&A
URD
Use Cases
UI Wireframe
Sequence Diagrams
SRS

Cong nghe su dung

Thanh phanCong nghePhien ban
RuntimeNode.jsES Modules
Web FrameworkExpress5.x
AI SDK@anthropic-ai/sdk0.52+
AI ModelsClaude (Haiku/Sonnet/Opus)4.5
FrontendVanilla HTML/CSS/JS-
ConfluenceConfluence DC REST APIv2
Data StorageJSON Files-
Auth (Confluence)Personal Access Token (Bearer)-

Cau truc thu muc

ba-agent-system/
├── package.json           # Dependencies & scripts
├── .env                    # Environment variables
├── src/
│   ├── index.js            # CLI entry point
│   ├── agents/             # Multi-agent implementations
│   │   ├── BaseAgent.js
│   │   ├── DiscoveryAgent.js
│   │   ├── AnalysisAgent.js
│   │   ├── DocumentationAgent.js
│   │   ├── UseCaseAgent.js
│   │   ├── VisualizationAgent.js
│   │   ├── ValidationAgent.js
│   │   └── PublishAgent.js
│   ├── config/
│   │   └── agents.config.js  # Model, prompt, temperature config
│   ├── core/
│   │   ├── Orchestrator.js   # Agent coordination
│   │   └── SessionManager.js # Session & artifact storage
│   ├── services/
│   │   ├── AIService.js      # Claude API wrapper
│   │   └── ConfluenceService.js # Confluence REST API
│   ├── storage/
│   │   └── sessions/         # JSON session files
│   └── web/
│       ├── server.js         # Express server + API routes
│       └── public/
│           ├── index.html    # Web UI (SPA)
│           ├── user-guide.html # End-user guide
│           └── tech-guide.html # This document

Yeu cau he thong

Cai dat

# Clone repository
git clone <repo-url>
cd ba-agent-system

# Cai dat dependencies
npm install

# Tao file cau hinh
cp .env.example .env
# Chinh sua .env voi API keys cua ban

# Chay web server
npm run web
# Truy cap http://localhost:3000

Cau hinh .env

BienMo taBat buoc
ANTHROPIC_API_KEYAPI key tu Anthropic ConsoleCo
CONFLUENCE_BASE_URLURL goc cua Confluence DC (vd: https://wiki.example.com)Khong
CONFLUENCE_API_TOKENPersonal Access Token cho ConfluenceKhong
PORTPort web server (mac dinh: 3000)Khong
Luu y: Khong commit file .env len git. File nay chua API keys nhay cam.

Multi-Agent System

He thong gom 7 agent chuyen biet, moi agent xu ly mot giai doan:

AgentChuc nangModelThinking
DiscoveryAgentHoi dap kham pha yeu cauHaiku 4.5 (Fast)Off
AnalysisAgentPhan tich & phan loai yeu cauSonnet 4.5 (Balanced)On
DocumentationAgentTao BRD, URDSonnet 4.5 / Haiku (edit)On / Off
UseCaseAgentTao Use CasesSonnet 4.5 / Haiku (edit)On / Off
VisualizationAgentTao diagrams (PlantUML)Sonnet 4.5On
ValidationAgentKiem tra chat luongSonnet 4.5On
PublishAgentTong hop & xuat banHaiku 4.5 (Fast)Off

AI Service

File: src/services/AIService.js

AIService la lop wrapper cho Anthropic SDK, cung cap:

Streaming

Tat ca API calls su dung streaming (messages.stream() + .finalMessage()) de tranh timeout. Cau hinh stream: true trong agents.config.js.

Session Manager

File: src/core/SessionManager.js

Quan ly session (project), features, va artifacts:

Data Structure

{
  "id": "session-uuid",
  "projectName": "Ten du an",
  "features": [{
    "id": "feature-uuid",
    "name": "Ten tinh nang",
    "currentPhase": "discovery",
    "artifacts": {
      "brd": { "source": { "content": "...", "confluencePageId": "..." } },
      "urd": { "content": "...", "version": 1, "confluencePageId": "..." },
      "usecases": { "content": "...", "version": 1 },
      "ui": { "content": "...", "version": 1 },
      "sequence": { "content": "...", "version": 1 },
      "srs": { "content": "...", "version": 1 }
    },
    "conversation": [...]
  }]
}

Confluence Service

File: src/services/ConfluenceService.js

Tich hop voi Confluence Data Center qua REST API:

MethodChuc nang
getContent(pageId)Lay noi dung trang
updateContent(pageId, spaceKey, title, content, version)Cap nhat trang
createPage(spaceKey, parentId, title, content)Tao trang moi
searchByTitle(spaceKey, title)Tim kiem theo ten
htmlToStorage(html)Chuyen HTML sang XHTML storage format
markdownToStorage(md)Chuyen Markdown sang XHTML
storageToText(xhtml)Chuyen XHTML sang plain text

Authentication

Su dung Bearer token (Personal Access Token):

Authorization: Bearer <CONFLUENCE_API_TOKEN>

Agent Configuration

File: src/config/agents.config.js

Moi agent co cau hinh rieng:

agents: {
  discovery: {
    model: MODELS.FAST,        // Haiku 4.5
    maxTokens: 8192,
    temperature: 0.7,
    enableThinking: false,
  },
  documentation: {
    model: MODELS.BALANCED,    // Sonnet 4.5
    maxTokens: 64000,
    temperature: 0.5,
    enableThinking: true,
    thinkingBudget: 32000,
    edit: {                    // Override cho che do edit
      model: MODELS.FAST,     // Haiku cho edit
      maxTokens: 64000,
      temperature: 0.3,
      enableThinking: false,
    },
  },
  // ... (xem chi tiet trong agents.config.js)
}

AI Models

ConstantModel IDSu dung choGia (Input/Output per 1M)
MODELS.FASTclaude-haiku-4-5Chat, edit, don gian$1 / $5
MODELS.BALANCEDclaude-sonnet-4-5Phan tich, tao tai lieu$3 / $15
MODELS.PREMIUMclaude-opus-4-5Task quan trong (chua dung)$15 / $75

System Prompts

Tat ca system prompts duoc dinh nghia trong agents.config.js muc CONFIG.prompts. Tat ca prompt yeu cau output bang tieng Viet.

Cac prompt key: discovery, analysis, documentation, documentationEdit, usecase, usecaseEdit, visualization, validation, publish, urdGeneration, urdUpdate, brdGeneration, discoveryFromBRD.

API Overview

Server chay tren Express 5.x, mac dinh port 3000. Tat ca API tra ve JSON.

Base URL: http://localhost:3000/api

Headers:
  Content-Type: application/json

Projects API

MethodEndpointMo ta
GET/api/projectsDanh sach project
POST/api/projectsTao project moi
GET/api/projects/:idChi tiet project
PUT/api/projects/:id/confluenceCau hinh Confluence
DELETE/api/projects/:idXoa project

Features API

MethodEndpointMo ta
GET/api/projects/:id/featuresDanh sach features
POST/api/projects/:id/featuresTao feature (voi BRD tuy chon)
GET/api/projects/:id/features/:fidChi tiet feature
POST/api/projects/:id/features/:fid/chatChat voi AI agent
POST/api/projects/:id/features/:fid/next-phaseChuyen giai doan tiep
POST/api/projects/:id/features/:fid/switch-phaseChuyen den giai doan cu the
DELETE/api/projects/:id/features/:fidXoa feature

Documents API

MethodEndpointMo ta
GET.../:fid/document-statusTrang thai tat ca tai lieu (bao gom confluencePageId)
POST.../:fid/generate-urdTao URD
POST.../:fid/generate-usecasesTao Use Cases
POST.../:fid/generate-uiTao UI Wireframe
POST.../:fid/generate-sequenceTao Sequence Diagrams
POST.../:fid/generate-srsTao SRS
POST.../:fid/documents/:docType/publishDay tai lieu len Confluence

Publish Endpoint

POST /api/projects/:id/features/:fid/documents/:docType/publish

Trong do :docType la mot trong: brd, urd, usecases, ui, sequence, srs.

// Tao trang moi
{ "createNew": true, "spaceKey": "BA", "parentPageId": "123" }

// Cap nhat trang co san (URL)
{ "confluenceUrl": "https://wiki.example.com/pages/viewpage.action?pageId=456" }

// Cap nhat trang co san (Page ID)
{ "confluencePageId": "456" }

Confluence API

MethodEndpointMo ta
GET/api/confluence/testTest ket noi Confluence
GET/api/confluence/spacesDanh sach spaces
GET/api/confluence/content/:pageIdLay noi dung trang
PUT/api/confluence/content/:pageIdCap nhat trang
POST/api/confluence/contentTao trang moi
POST/api/confluence/searchTim kiem trang

Lenh chay

LenhMo ta
npm run webChay web server (production)
npm run dev:webChay web server voi auto-reload
npm startChay CLI mode
npm run chatChay chat mode
npm testChay test
npm run infoHien thi thong tin he thong

Luu tru du lieu

Du lieu duoc luu duoi dang JSON files tai src/storage/sessions/. Moi project la mot file JSON chua tat ca features, artifacts va conversation history.

He thong hien tai su dung file-based storage. De chuyen sang database, can thay the cac method trong SessionManager.js.

SSE Streaming

He thong ho tro Server-Sent Events (SSE) cho real-time streaming tu AI:

// Server-side (server.js)
function setupSSE(res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'X-Accel-Buffering': 'no',
  });
}

function sendSSE(res, data) {
  res.write(`data: ${JSON.stringify(data)}\n\n`);
}

// Cau hinh stream trong agents.config.js
ai: { stream: true }

Cac endpoint ho tro SSE: /chat, /next-phase, /generate-brd, /generate-urd, /urd/chat.

Khi stream=true trong config, server tra ve SSE events voi cac type:

// Frontend - Xu ly SSE stream
const response = await fetch(url, { method: 'POST', body: JSON.stringify(data) });
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });

  // Parse SSE lines
  const lines = buffer.split('\n');
  buffer = lines.pop();

  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const event = JSON.parse(line.slice(6));
      if (event.type === 'text_delta') {
        // Append text to UI
      } else if (event.type === 'message_complete') {
        // Handle complete response
      }
    }
  }
}