AI Workspace nội bộ · Nexus Chat GA · Nexus Dev Beta · Nexus Knowledge Live

LTS Nexus Platform
Tài liệu Kỹ thuật & Hướng dẫn

Một nơi duy nhất để mọi phòng ban chạy AI agent trên công việc chuyên môn của mình — dưới sự kiểm soát tập trung về model, skill, ngân sách và audit. Tài liệu này tổng hợp toàn bộ tính năng, cách sử dụng, và chiều sâu kỹ thuật của hệ thống.

0Sản phẩm Nexus-*
0Dịch vụ Platform nền
0Tính năng đã build
0Tiết kiệm token nhờ cache
Nexus là gì

Không phải "thêm một chatbot" —
mà là một Workspace Shell

Nexus host nhiều "sản phẩm Nexus-*" (Chat, Dev, Knowledge, Design…) trên cùng một nền tảng AI + governance. Toàn bộ được tổ chức theo mô hình 3 lớp — đọc từ trên xuống là hiểu toàn hệ thống.

Lớp 1 · Vỏ Governance

🔵 Workspace

Ranh giới quản trị — không phải "1 dự án". Quyết định: ai vào được, dùng model nào, skill nào, ngân sách bao nhiêu, log nằm đâu, ai duyệt gì. Một user thuộc nhiều workspace; mọi action đều gắn với một workspace cụ thể (không có "global session").

RBAC: ADMIN / OWNER / MEMBERBudget capGitHub bindingGuardrail configAudit log
▾ chứa ▾
Lớp 2 · Cái user DÙNG

🟢 Products (Nexus-*)

Mỗi sản phẩm là một bề mặt độc lập cho một use-case rõ ràng. User mở Workspace → chọn sản phẩm → vào ngay. Sản phẩm release độc lập, không refactor lẫn nhau.

💬 Nexus Chat⚙️ Nexus Dev📚 Nexus Knowledge🎨 Nexus Design👥 Nexus Cowork
▾ dùng ▾
Lớp 3 · Backbone dùng chung

🔵 Platform

7 dịch vụ nền. Tất cả product đều xài chung — không product nào tự build lại. Đảm bảo governance + cost control + audit là một nguồn duy nhất, không phân tán.

IdentitySkill RegistryModel GatewayAgent RuntimeTask SpineObservabilityIntegrations
🎯

Tư duy theo "tôi muốn làm gì"

Người dùng vào workspace, thấy thẻ "Nexus Chat" / "Nexus Dev" — biết ngay cái nào hợp việc của mình, không cần hiểu "module nào".

🧩

Product release độc lập

Nexus Chat ship feature mới không cần đụng Nexus Dev. Thêm sản phẩm sau này = "cắm vào Platform".

🛡️

Platform không bị fork

Mọi product dùng chung Identity, Model Gateway, Skill Registry — governance + cost + audit tập trung.

Catalog sản phẩm

Năm bề mặt Nexus-*

Mỗi sản phẩm phục vụ một use-case riêng. Ba sản phẩm đầu đã chạy thực tế; hai sản phẩm còn lại đang trong lộ trình.

💬
GA-ready

Nexus Chat

Cho ai: mọi nhân viên (kỹ thuật + phi kỹ thuật).

Trợ lý trò chuyện: hỏi/đáp, sinh tài liệu (DOCX/XLSX/PPTX/MD/HTML), tóm tắt, dịch, brainstorm. Có pin file, memory, prompt cache, i18n. Không tự chạy quy trình nhiều bước.

33/33 featureArtifacts đa định dạngSource tree + Ask agentSkill authoring
⚙️
Beta

Nexus Dev

Cho ai: team Dev LTS (~50 user).

Giao task → pipeline BA → Dev → QC chạy tự động trong sandbox → mở PR → người duyệt → merge. Trợ lý xử lý task lặp lại có HITL gate, không thay thế lập trình viên. Delivery lifecycle (Presale → Dev → Bảo trì) qua Engagement cockpit.

20/20 featureRunner FSMEnsemble + SubagentDelivery lifecycle
📚
Live

Nexus Knowledge

Cho ai: mọi member cần tra cứu/đóng góp tri thức.

Smart Wiki: process docs, CV/Person directory, case studies, biểu mẫu. Tag/folder, full-text search, graph view + backlink (kiểu Obsidian), review workflow, và RAG tự nạp vào chat (pgvector).

Doc CRUD + 4 kindPerson directoryGraph + backlinkRAG retrieval
🎨
Future

Nexus Design & Cowork

Ý tưởng tương lai.

Design: thiết kế UI/diagram qua chat + Figma. Cowork: nhiều người + AI cùng làm trên một artifact (doc/spec/diagram). Chưa có spec, chưa có code.

Chưa scope
Bản đồ tính năng

Hơn 100 tính năng, theo từng module

Chọn một mục để xem chi tiết danh sách tính năng kèm trạng thái triển khai.

💬 Nexus Chat 33
⚙️ Pipeline 22
🔒 Agent Exec 22
⏰ Scheduler 6
🏢 Workspace 15
📚 Knowledge 14
🧩 Agent Studio 12
🧠 Skill & Pack 15
🤖 Model Gateway 9
📋 Task & Auth 19
📡 Observability 5
F01-F06
Quản lý session

List / tạo / xem chi tiết / đổi tên (inline) / archive-unarchive session chat, kèm authz helper kiểm soát quyền truy cập.

Done
F07-F09
Turn loop + history + SSE

Gửi message → LLM xử lý trong một "turn"; xem lịch sử; nhận event realtime qua Server-Sent Events.

Done
F10-F11
Pin file + Memory health

Ghim file repo vào ngữ cảnh để LLM tham khảo (refresh được); widget hiển thị "sức khỏe" bộ nhớ (token, context window, tokens saved).

Done
F15-F16
Source tree + File viewer + Ask-agent

Duyệt cây file repo (cache 60s), xem nội dung (~256KB), và chèn đường dẫn file vào ô chat để hỏi agent.

Done
F17-F19
Workbench shell + Onboarding + Layout pref

Giao diện chính: icon rail + panel resizable, checklist hướng dẫn người mới, lưu preference layout theo user.

Done
F20-F23
Slash autocomplete + Streaming + Stop

/ gợi ý lệnh (UTILITY/PROMPT/TASK), reply stream realtime (202 + SSE delta), dừng giữa chừng.

Done
F25
Edit message + Regenerate

Chỉnh sửa tin nhắn đã gửi hoặc yêu cầu LLM tạo lại câu trả lời.

Done
F26
Run as Task

Chuyển một hội thoại thành task chạy qua pipeline Nexus Dev (gate bởi cờ WORKBENCH_PIPELINE_ENABLED).

Done
F28-F30
Search + Cost badge + i18n

Tìm kiếm session & trong hội thoại (Cmd/Ctrl+F), lưu model/cost mỗi message, giao diện + agent song ngữ EN/VI.

Done
F33
Publish chat to workspace

Chuyển session từ PRIVATE → WORKSPACE (chia sẻ cho cả workspace, read-only với người xem).

Done
F31-F32
Subagent spawn + Skill authoring

LLM spawn subagent read-only (card "🌿 spawned N"); tool propose_skill_draft / commit_skill_draft tạo skill draft (2-turn confirm); FE SkillProposalChip dialog Confirm/Edit/Discard.

Done
F01-F04
Agent Role + Pipeline Definition CRUD

Tạo/sửa role (BA, DEV, QC, custom) và pipeline với các stage có thứ tự; seed sẵn pipeline-sdlc-v1. Role đang dùng không archive được.

Done
F05-F07
Start / list / detail run + Resume

Chạy pipeline trên task (claim atomic: 1 run active/task), xem artifact từng stage, resume từ stage fail.

Done
F08, F13
Worker stage executor + Timeout

BullMQ consumer chạy stage (spawn sandbox, execute agent, capture artifact); job timeout + reconcile 5 phút chống leak lock.

⚠ QC
F09-F10, F22
HITL Gates: approve/reject + Ask-human

Gate phê duyệt giữa các stage (có lịch sử), và gate "ask-human" để agent hỏi con người một câu rồi tiếp tục.

Done
F11-F12
Stop run + Sandbox orphan cleanup

Dừng run (graceful → force kill); công cụ admin liệt kê + retry dọn sandbox mồ côi.

Done
F14-F16
Run events + Cost rollup + Raise budget

Bảng event + rollup chi phí (event-sourcing-lite append-only); nâng budget khi stage vượt thay vì bỏ qua.

Done
F23
Stage Ensemble

Stage chạy N variant song song (mỗi variant một SessionRun), judge chọn winner, chỉ winner push git (two-phase, không synth diff).

Done
F25
Run log viewer 3 cột

Trang xem-only: stage timeline · event stream realtime · cost/artifacts, có filter event + cảnh báo guard.

Done
F24
Subagent spawn fan-out

Stage spawn N subagent (depth-1, flat) — tương tự variant nhưng kèm orchestration config + lineage card (SubagentNote FE).

Done
F01-F03
Runner pairing + list/revoke + heartbeat

Pairing code (TTL 10') để nối "Personal Runner" trên máy cá nhân; rename, revoke tức thì, heartbeat xác nhận online.

Done
F04-F07
Claim/report stage + Lane routing

Personal runner claim stage (key + repo token per-stage); tự chọn lane PERSONAL nếu online, fallback SERVER. Checkbox "Chạy trên máy tôi".

Done
F08-F09
Microagent injection + Tool enforcement

Inject enforced SYSTEM skill (read-only, mount ngoài repo); ánh xạ toolKeys → env, dọn sạch không để lại residue.

Done
F10-F11
Layer-4 guards + Post-validator (Layer-3)

Secret-scan, protected-branch, budget pre-check; validator chấm artifact+diff trước gate/advance.

Done
F16-F17
Egress allowlist + Runtime sentinel

Squid sidecar chặn egress (SERVER lane); sentinel parse từng action, deny bash nguy hiểm, kill ≤10s nếu vi phạm.

Done
F18-F21
Adversarial suite + Validator v2 + Compliance dashboard

CI gate ≥6 vector tấn công; validator 2-vote FAIL_CLOSED; dashboard tuân thủ + nightly digest 04:30.

Done
F13-F15
Integration Phase 1 — Docker env provisioning

Tạo isolated Docker network (--internal, no egress), start service containers với resource caps + health polling; connectSandboxToIntegrationNetwork; inject env vars (connection strings) vào sandbox. Cleanup đăng ký trên TẤT CẢ exit path (fail/ask-human/gate/succeed). Sandbox agent KHÔNG cầm Docker socket — trust boundary giữ nguyên ADR-080.

Done
F22
Subagent child sandbox (trust parity)

Sandbox con có đủ trust-layer (proxy, sentinel, egress, caps) nhưng KHÔNG push git.

WIP
F01-F03
Schedules CRUD + Run now + Last-run

Tạo/sửa/xóa lịch (cron) theo workspace, trigger thủ công "Run now", theo dõi lần chạy cuối (lastRunAt/Status).

Done
F04
Kind ONCE + AFTER_EVENT

Thêm loại lịch: chạy một lần (ONCE) hoặc kích theo sự kiện (task.done, pr.merged, run.failed, gate.waiting…).

Done
F05-F06
Guardrails + Domain-event bus

maxRunsPerDay, taskBudgetUsd per-run, onFail (alert/retry/stop); event bus 5 điểm emit + event-listener match/filter/rate-cap.

Done
F01-F05
Workspace CRUD + Archive

List (ADMIN any, MEMBER assigned), tạo (ADMIN-only), xem chi tiết, sửa metadata, archive/unarchive (soft-delete).

WIP
F06-F07
Bind / Unbind GitHub repo

Kết nối repo qua GitHub App (mint token on-demand per session); ngắt kết nối khi cần.

WIP
F08-F09
Agent config + Guardrail config

Chọn model mặc định, pipeline definition, skill set; cấu hình budget cap (monthBudgetUsd), post-validator, gate timeout.

WIP
F10, F14
Dashboard + Card stats

Metrics: spend tháng, top run, số session; card hiển thị quick stats (member, run count).

WIP
F11-F13, F15
Member role + Leave + Shell UX

Đổi vai trò member↔owner (last-owner guard), tự rời workspace; dark mode + bottom-nav mobile.

Done
KN F01-F03
Doc CRUD + 4 kind + vòng đời

Tạo/sửa/xem/xóa tài liệu với kind = PROCESS · CASE_STUDY · TEMPLATE · GENERIC; trạng thái DRAFT → PUBLISHED → ARCHIVED; folder + tag + body Markdown.

Done
KN F04-F05
Full-text search

Tìm kiếm toàn văn bằng Postgres tsvector + GIN index (raw SQL), lọc theo kind/tag/folder, rank theo độ liên quan.

Done
KN F06-F07
Graph view + Backlink

Wiki-link giữa các doc (KnowledgeLink) → đồ thị tri thức kiểu Obsidian, xem backlink "doc nào trỏ tới đây", điều hướng theo liên kết.

Done
KN F08-F09
Person directory (CV)

Hồ sơ nhân sự: title/department/skills/projects + link file CV. Tra cứu chuyên gia theo kỹ năng, gắn vào case study.

Done
KN F10-F11
Attachment + dedupe

Upload PDF/DOCX… qua presigned URL, dedupe bằng SHA-256, giới hạn dung lượng theo workspace.

Done
KN F12
RAG vào chat

Embedding pgvector (text-embedding-3-small 1536-dim, IVFFlat) + endpoint knowledge/ask; chat tự retrieve top-K (best-effort, không block turn). Reindex + rag-config theo workspace.

Done
KN F13-F14
Review workflow + Contributor RBAC + Template

Gate request-review → approve/reject trước khi publish; phân quyền contributor; doc confidential; "use-template" để dựng doc mới từ biểu mẫu.

Done
AS F01
5 entity + Imports trong một studio

Settings → Agent Studio: Skills · Roles · Packs · Flows · Tools · Imports — layout danh sách + editor, cross-navigation giữa các entity liên kết.

Done
AS F02-F03
Flow canvas + Stage panel

Dựng luồng đa-agent trực quan bằng @xyflow/react (flow-canvas), chỉnh từng stage qua side-panel, gắn role/skill/tool cho mỗi chặng.

Done
AS F04-F05
Pack composer + Role/Skill detail

Gộp role + stage + skill + cron thành Pack; editor chi tiết cho Role, Skill, Tool với manifest drawer + quick-create/run-test.

Done
AS F06-F07
Git/zip import + coverage

Import bundle từ Git URL hoặc .zip → canonical manifest → coverage report → migrate thành SkillDraft + pack-draft (INACTIVE) chờ duyệt (ADR-055/063).

Done
AS F08-F09
Agent Library (org-scope) + Link

Admin quản thư viện SYSTEM /admin/agent-library (Skills/Roles/Packs/Flows/Tools); workspace subscribe bằng WorkspaceSkillLink/FlowLink — tham chiếu, không clone (ADR-068).

Done
AS F10-F12
Library Browser + Manifest + Propagation guard

Workspace "kéo" component từ Library qua Library Browser; manifest drawer xem chi tiết; usage count + cảnh báo lan truyền + danger zone khi sửa entity dùng chung.

Done
SKILL F01-F02
Skill CRUD theo scope

Tạo/sửa/xóa skill với RBAC theo scope: SYSTEM (admin), WORKSPACE (owner), USER (self). SYSTEM skill không xóa được.

Done
SKILL F03-F04
Fork + Promote

USER fork skill WORKSPACE/SYSTEM (lưu lineage parentSkillId); request promote USER→WORKSPACE, owner duyệt.

Done
SKILL F08-F10
Import bundle + Migrate + Artifact viewer

Upload .zip Claude Code hoặc Git URL → canonical manifest → coverage report → migrate thành SkillDraft + pack-draft. Viewer cho script đính kèm.

Done
SKILL F06-F07
Chat-authored draft + Review

Skill viết qua chat vào staging table (PENDING) — KHÔNG live cho tới khi human approve ở Agent Studio. Tool propose_skill_draft / commit_skill_draft; FE SkillProposalChip 2-turn confirm.

Done
PACK F01-F03
Pack Builder no-code wizard

4 bước: intake → AI draft (prefill role/stage/skill/cron) → review → publish atomic (1 transaction).

Done
PACK F04-F05
Pack template save/load + re-validate

Lưu bundle thành template để tái dùng; load → prefill wizard + re-validate (model ACTIVE? skill? cron hợp lệ?).

WIP
MODEL F01
Smart model routing

Chat-only: route model theo heuristic độ phức tạp (0-100) + LLM-judge borderline + budget guard. Stage thì pin model tường minh.

Done
MODEL F02-F03
Model catalog + Virtual key

Nexus là source-of-truth → push LiteLLM; admin tạo workspace key (secret reveal 1 lần), revoke notify proxy.

Done
MODEL F04-F06
Budget cap + Spend view + Fallback

monthBudgetUsd hard-block 3 điểm enforce; spend theo ws/task/ngày + drift badge; fallback 1-step khi primary 5xx/429/timeout.

Done
MODEL F07-F09
Eval suite + Vendor allow + Ensemble

So sánh primary vs fallback; allowlist vendor theo ws × skill; ensemble parallel models + judge chọn winner.

Done
TASK F01-F08
Task board + State machine

Kanban (BACKLOG/RUNNING/WAITING/REVIEW/DONE/FAILED), tạo/sửa/cancel/archive; state machine atomic lock (ADR-004).

WIP
TASK F09-F11
Mark done + PR-merged webhook + Events SSE

Hoàn thành thủ công, hoặc GitHub webhook PR merged → auto DONE + emit domain event; stream event realtime.

Done
TASK F12-F13
Artifact viewer + PR body summary

FE render story/diff/test-report (JSON fallback, không raw HTML); compose PR body kèm artifact summary (cap 50 files, 8KB).

Done
AUTH F01-F03
Sign in + JWT session + Admin users

Username/password (bcrypt cost 12 + rate-limit Redis), JWT stateless, admin quản lý user (reset password, create).

Done
SYS F01-F06
Members + Audit log + Profile

List/add/remove member (last-owner guard); audit log filter action/actor/target/date + export CSV; profile + đổi mật khẩu.

Done
OBS F01
Notifications (bell + SSE)

Thông báo realtime (chuông + badge unread), mark read/read-all, click → điều hướng tới target (gate, stage failed…).

Done
OBS F02-F03
Health dashboard + Liveness probe

Worker heartbeat + status (Redis), queue depth; /api/healthz công khai không lộ chi tiết.

Done
OBS F04-F05
Audit UX + Cost dashboard

Filter username/quick-filter/target-link + export CSV; top-10 run 30 ngày, spend theo ws/task/ngày (rollover-aware).

Done
Hướng dẫn sử dụng

Bắt đầu trong vài bước

Chọn hành trình bạn quan tâm — mỗi hành trình là một quy trình thao tác đầu-cuối, dành cho mọi người dùng.

💬 Dùng Nexus Chat
⚙️ Chạy một Task (Dev)
🏢 Lập Workspace mới
🧠 Skill & Pack Builder
💻 Personal Runner
1

Mở Workbench

Vào workspace → thẻ Nexus Chat → "Enter →". Bạn vào màn hình toàn cảnh /workspaces/[id]/workbench với icon rail bên trái (Sessions · Tasks · Files · Settings).

2

Tạo hoặc chọn hội thoại

Ở panel Sessions, tạo session mới hoặc mở session cũ. Mỗi member đều tạo được session riêng (PRIVATE), có thể Publish ra WORKSPACE để chia sẻ.

3

Trò chuyện & dùng Slash command

Gõ tin nhắn (Enter để gửi). Gõ / để mở gợi ý lệnh — UTILITY (tiện ích), PROMPT (mẫu prompt), TASK (chuyển sang chạy task). Reply hiện stream realtime; nút Stop dừng giữa chừng.

4

Pin file & hỏi về code

Mở panel Files → duyệt cây repo → bấm "Ask agent" để chèn đường dẫn vào ô chat. Ghim file (pin) để LLM luôn có ngữ cảnh đó. Thanh memory health cho biết tokens đã tiết kiệm + chi phí.

5

Đính kèm & sinh artifact

Bấm 📎 để paste/drag file/ảnh (upload qua presigned URL). Agent có thể sinh artifact MD / HTML / DOCX / XLSX / PPTX — hiện trong panel xem riêng, tải về được.

6

Chỉnh sửa, regenerate, fork

Trên mỗi bong bóng: edit message, regenerate câu trả lời, hoặc fork để tách nhánh hội thoại mới. Tìm trong hội thoại bằng Cmd/Ctrl+F.

1

Tạo task

Vào Nexus Dev / Tasks → board Kanban /workspaces/[id]/tasks → "Tạo task". Nhập tiêu đề, mô tả, branch, người phụ trách. Task vào cột BACKLOG. Hoặc từ Chat: tab Task → "Run as Task".

2

Khởi chạy pipeline

Mở task → tab Pipeline → "Start run". Pipeline mặc định pipeline-sdlc-v1 (BA → Dev → QC) chạy tuần tự, mỗi stage trong một sandbox riêng. Có thể chọn "Run on my machine" nếu có Personal Runner online.

3

Theo dõi realtime

Mở Run log viewer /tasks/[id]/runs/[runId]: 3 cột — stage timeline · event stream · cost rollup. Pause/Play/Refresh, filter loại event, cảnh báo guard.

4

Duyệt HITL gate

Khi pipeline tới gate phê duyệt, task chuyển WAITING + bạn nhận notification. Card gate cho phép Approve / Reject kèm lý do. Gate "ask-human" thì agent hỏi một câu — bạn trả lời để tiếp tục.

5

Quản lý chi phí

Nếu stage vượt budget, run PAUSE (không fail) — bạn bấm "Raise budget" để cấp thêm rồi resume. Mọi chi phí được rollup theo stage, hiển thị 3 nơi (gate card, PR body, dashboard).

6

Review PR & hoàn thành

Stage cuối mở Pull Request kèm artifact summary → task chuyển REVIEW. Bấm "Review PR" để xem trên GitHub. Khi PR merged, webhook tự đánh dấu task DONE (hoặc bấm "Complete" thủ công).

1

Tạo workspace

Vào /workspaces → "New workspace" (ADMIN-only). Nhập tên + mô tả. Checklist "Getting Started" sẽ dẫn bạn qua các bước thiết lập.

2

Gắn GitHub repo

Settings → General → "Connect GitHub" → authorize App → chọn repo. Pipeline sẽ dùng repo này để clone + push PR (token mint on-demand, không lưu PAT dài hạn).

3

Cấu hình Agent

Tại General → Agent config: chọn default model, pipeline definition, skill set. Trong Settings → Chat đặt chat model, task model, ngân sách chat USD.

4

Đặt Guardrails

Settings → Dev → Guardrails: max iterations (30), timeout (1800s), monthBudgetUsd hard cap, protected branches, bật post-validator. Settings → Models để quản lý vendor allowlist.

5

Mời thành viên

Settings → Members → "Add member" (lookup username/email) → chọn role (member/owner). Đổi role hoặc xóa member (không xóa được owner cuối cùng).

6

Theo dõi Insights

Settings → Insights: phân bố task theo state, pipeline run 7 ngày, spend tháng/lifetime, cache hit rate — để nắm sức khỏe workspace.

1

Mở Agent Studio

Settings → Agent Studio: 6 tab — Skills · Roles · Packs · Flows · Tools · Imports. Layout 2 cột: danh sách trái + editor phải.

2

Tạo Skill

Tab Skills → "Quick Create". Chọn scope (USER private / WORKSPACE shared / SYSTEM admin), nhập tên + nội dung prompt, đánh dấu enforced nếu là quy tắc bắt buộc.

3

Fork & Promote

Fork một skill WORKSPACE/SYSTEM về USER để tùy biến. Khi hài lòng, "Promote" USER → WORKSPACE; owner duyệt là skill thành chung cho team.

4

Import từ Claude Code bundle

Tab Imports → upload .zip hoặc dán Git URL → hệ thống evaluate → coverage report → "Migrate" tạo SkillDraft + pack-draft (INACTIVE) để review.

5

Dùng Pack Builder no-code

/workspaces/[id]/packs/new → wizard 4 bước: mô tả task → AI prefill role/stage/skill/cron → review (chỉnh stage, thêm gate) → publish atomic.

6

Thư viện Org (Agent Library)

Admin vào /admin/agent-library — thư viện cấp org. Workspace có thể "kéo" skill/role/pack/flow từ Library về dùng (Library Browser).

1

Sinh pairing code

Vào /profile → mục Runners → "Generate pairing code". Code có TTL 10 phút, dùng một lần.

2

Ghép máy cá nhân

Trên máy local chạy agent CLI: nexus-agent pair <code>. Runner đăng ký xong sẽ hiện trạng thái ONLINE, gửi heartbeat định kỳ.

3

Chạy task trên máy mình

Khi tạo/chạy task, tick "Run on my machine" (chỉ hiện nếu runner online). Stage claim về máy bạn, thực thi local; nếu runner offline thì tự fallback SERVER lane.

4

Quản lý & thu hồi

Rename runner; "Revoke" để vô hiệu hóa tức thì (401). Admin xem toàn bộ runner ở /admin/runners.

Kiến trúc & Stack

Một codebase, hai tiến trình

Nexus là ứng dụng fullstack Next.js 15. Cùng một mã nguồn, build thành hai tiến trình: web (UI + API + SSE) và worker (BullMQ — pipeline runner, scheduler, adapter).

👤 Người dùng (web)trình duyệt
Caddyreverse proxy · auto-HTTPS
Next.js App (web)App Router · Auth.js v5 JWT · Prisma · SSE endpoint
↓ enqueue qua Redis
PostgreSQL 16Prisma · state · audit · event
RedisBullMQ · pub/sub · lock
Workerpipeline.worker · scheduler · adapter
LiteLLM Proxy :4000routing · virtual key mint · budget cap · spend log
OpenHands SandboxDocker · agent loop · git ops
Claude (Sonnet/Haiku)Anthropic API
OpenRouterQwen / DeepSeek fallback
GitHubrepo · PR · webhook (HMAC)
Tách tiến trình = request/response HTTP luôn responsive ở web; còn các quy trình dài hơi (pipeline runner FSM, scheduler) chạy nền ở worker — retry, backpressure được. BullMQ queue là hợp đồng giữa hai bên.
Tech Stack
Next.js 15App Router · React 19
TypeScript 5type-safe toàn stack
PostgreSQL 16+ Prisma 6 ORM
Redis 7BullMQ 5 · pub/sub · lock
Auth.js v5credentials + JWT · bcrypt
shadcn/uiRadix · Tailwind 3
LiteLLMmodel gateway · budget
OpenHands v1.21+sandbox agent · headless
OctokitGitHub App · token mint
Artifact libspptxgenjs · xlsx · html-to-docx
@xyflow/reactflow canvas (Agent Studio)
Docker Compose+ Caddy · Ubuntu 24.04
Điểm nổi bật thiết kế

Những quyết định tạo nên Nexus

Các pattern và ADR (Architecture Decision Records) định hình cách hệ thống vận hành an toàn, tiết kiệm và có thể mở rộng.

ADR-025 / 027

🧬 Role-as-Data

Mỗi role (BA, Dev, QC) là một entity = system prompt + tool cho phép + model. Thay prompt không cần code — config qua UI. Pipeline có thể override defaults per stage.

ADR-024

⚡ Prompt Cache 3-Breakpoint

Chia prompt thành các tầng tự nhiên, cache theo từng tầng (TTL 5'). Tiết kiệm ~83% input token trên session 30 lượt. Theo dõi hit-rate per session.

ADR-019

🎯 Smart Model Routing

Heuristic score 0-100 (độ dài, file ref, keyword, role) → tier cheap/standard/premium. Borderline 60-80 gọi Haiku judge. Budget thấp → tự downgrade tier.

ADR-021 / 047

🔀 Ensemble + Code-Exec

Task khó (score ≥85) chạy N model song song → judge chọn winner. Skill code-first-reasoning ưu tiên viết Python/bash chạy thật thay vì suy luận chay.

ADR-020

🛡️ 4-Layer Skill Enforcement

Quy tắc enforce qua 4 tầng: prompt priority (L1) → data flag (L2) → post-validator (L3) → tool guards regex/branch/budget (L4). Defense in depth — không tầng nào sót.

ADR-031

🔑 Virtual Key per Stage

Mint LiteLLM key riêng mỗi stage (max_budget cap cứng tại proxy) → revoke sau khi xong. Agent loop "điên" cũng không vượt ngân sách dù worker chết.

ADR-002

🎫 GitHub Token Mint-on-Demand

Không lưu PAT dài hạn. Mint installation token ngắn hạn per session, scope đúng một repo → giảm attack surface nếu lộ.

ADR-026

📦 Sandbox Isolation

Mỗi SessionRun = một Docker container + một git branch riêng. Sentinel kill ≤10s khi vi phạm; squid sidecar chặn egress; caps RAM/CPU/pids.

ADR-011 / 029

🤝 HITL Gates

Gate phê duyệt giữa pipeline (tùy chọn) + gate cuối là PR (bắt buộc, structural). Con người luôn nắm điểm kiểm soát trước khi merge.

ADR-032

👤 Credentials + JWT Auth

Thay Entra SSO bằng username/password + JWT stateless. Chạy offline, admin kiểm soát vòng đời user. passwordChangedAt + active invalidate token cũ.

ADR-031

📜 Event-Sourcing-Lite

Bảng PipelineEvent append-only là source of truth cho cost & audit. SSE / audit / cost rollup đều derive từ đây — không 3 bề mặt tự cộng.

ADR-004

🔒 Atomic Task Lock

Task là đơn vị tuần tự — chỉ 1 run active cùng lúc (activeRunId @unique). Mọi state transition là conditional UPDATE atomic, tránh race condition.

Luồng dữ liệu

Hệ thống vận hành thế nào

Hai luồng cốt lõi: một lượt Chat và một lần chạy Pipeline. Cuộn xuống để xem từng bước "thắp sáng" tuần tự.

💬 Luồng một lượt Chat — từ message đến artifact

Nhận & validate message sendMessage

Chỉ creator được gửi. Chặn nếu session ARCHIVED hoặc đang generate (1 generation/session). Re-scan secret server-side → có secret + không override = 422.

Persist message USER transaction

Ghi ChatMessage role=USER + attachments. Emit SSE message.created. File text/json được inline vào bản gửi LLM (DB vẫn giữ content sạch).

Gate + Routing + Ensemble plan startReply

Budget gate (chat + month cap). Smart routing chọn model theo score. Ensemble plan nếu score ≥85 + đủ điều kiện. Gating tool (subagent/skill/exec) theo keyword.

Build prompt runGeneration

Song song fetch: skills (SYSTEM/WS/USER) + pinned files + summaries + recent messages. RAG hook retrieve top-K knowledge (best-effort, timeout 800ms). Ghép 4 band + đặt cache breakpoint.

Gọi Model Gateway + Stream 3 nhánh

Ensemble: fan-out N model → judge chọn winner. Tool turn: model gọi tool → app chạy → re-invoke. Single stream: mỗi delta → SSE message.delta tăng seq.

Post-check + Persist transaction

Resolve [BLOCKED] marker. Update message (cost/tokens/cache), session total, record workspace spend. Emit message.completed. Trigger summarize nếu context > 60% window.

⚙️ Luồng Pipeline — task đến PR

Trigger triggerRun

Mọi nguồn (chat / api / webhook / schedule) funnel qua một cửa. Tạo Task → audit task.triggered → gọi startRun.

startRun snapshot

Resolve PipelineDefinition (mặc định BA→Dev→QC). Snapshot definition (sửa config sau không ảnh hưởng run). Tạo branch, chọn lane, tạo SessionRun stage đầu, enqueue BullMQ sau commit. Lock: 1 active run/task.

Stage executor worker/stage.ts

Claim atomic (1 worker thắng). Tool env overrides. Budget pre-check (Layer-4). Vendor allow expansion. Mint virtual key riêng per stage (TTL + max_budget cap). Clone repo, inject repo-map.

Spawn OpenHands sandbox

Chạy headless, parse JSONL stream. Sentinel deny bash + secret-scan, kill ≤10s nếu vi phạm. Egress squid. Poll usage ~10s: 80% → warning, ≥budget → kill + PAUSE. Đọc artifact .nexus/artifact.json.

Guards + Post-validator Layer-3/4

Pre-push: secret-scan-on-diff + protected-branch trên staged diff. Commit (deterministic, no token). Validator chấm artifact+diff vs enforced rules (2-vote, FAIL_CLOSED opt-in).

HITL Gate approve/reject

Gate giữa stage (opt-in): run WAITING_APPROVAL → Approval row → emit gate.waiting → render gate card. Approve atomic 3-way. Timeout 24h → PAUSE.

Advance / Complete → PR completeRun

Còn stage → tạo attempt kế + enqueue. Hết stage → dispatch adapter git-pr mở PR kèm cost line. Run SUCCEEDED ⇔ PR opened. Task → REVIEW → DONE (manual hoặc PR-merged webhook).

Luồng Event giữa các module

📨 Transport

Redis pub/sub → SSE. Channels: chat-session:<id>, task:<tid>, workspace:<wsId>, user:<id>, và domain:events riêng cho event bus.

🔗 Domain-event bus

Taxonomy v1 đóng: task.done, pr.merged, run.failed, gate.waiting, schedule.run_failed → event-listener match AFTER_EVENT schedules → triggerRun.

Invariants chốt: 1 SessionRun = 1 sandbox = 1 git branch · tuần tự trong stage, flat parallel ở subagent (depth=1) · 1 active run/task · final gate bắt buộc · code mutation chỉ qua agent + PR (viewer read-only) · enforced skills áp đủ 4 layer · routing auditable · RAG augment không bao giờ block chat turn.
Luồng Prompt

Prompt được dệt từ 4 band + 3 cache breakpoint

Mỗi lượt chat, prompt được lắp ráp từ 4 tầng ngữ nghĩa, ghép bằng \n\n---\n\n. Ba tầng đầu được cache (TTL 5'), tầng cuối luôn tươi — đó là bí quyết tiết kiệm ~83% token.

BP-1Band 1 — SYSTEM✓ CACHE

Enforced rules (skills enforced=true, bọc <enforced-rules priority="CRITICAL"> đặt đầu tiên — ADR-020 Layer 1) + system prompt + RAG <knowledge> + skills guidance (non-enforced) + repo info + dòng tĩnh "reply in same language" (giữ tĩnh để không phá cache key).

BP-2Band 2 — PINNED FILES✓ CACHE

Các file đã ghim, dedup theo (path, sha), bọc <pinned file sha stale-since>. File stale vẫn inject content cũ kèm banner cảnh báo. Không bao giờ bị summarize.

BP-3Band 3 — SUMMARY✓ CACHE

Rolling summaries của hội thoại, bọc <summary range tokens>. Nguồn = selectRelevantSummaries() — semantic ranking (pgvector cosine) nếu bật, không thì newest-first.

Band 4 — RECENT (verbatim)✗ FRESH

Recent messages render ROLE: body — luôn tươi, không cache. File ref dedup trong window (lần đầu inline, sau đó <fileref/>). Pre-flight trim: nếu vượt 90% window → drop oldest recent + enqueue summarize.

🧠

Skill resolution

SYSTEM + WORKSPACE + USER. Trên slug collision: USER > WORKSPACE; SYSTEM keyed riêng, không bị override. USER skill chỉ áp trong session của chính user. Skill draft PENDING không được nạp tới khi human duyệt.

⚙️

Cache chỉ với Anthropic

shouldCache() chỉ true khi model bắt đầu anthropic/. Khi đó system content là mảng content-block, mỗi segment mang cache_control: ephemeral ở block cuối. Provider khác → strip thành string thường.

📊

Memory health

Theo dõi pinnedCount/tokens, summaryCount, tokensSaved (Σ meta), totalTokens, totalCost — nuôi widget memory + budget banner cho user thấy rõ chi phí.

🤖 Luồng Model Gateway — routing & fallback

Score độ phức tạp scoreComplexity

Heuristic 0-100 deterministic: độ dài + fileRefCount×5 + hasImage(+20) + HIGH keyword (refactor/design/architecture) − LOW keyword (explain/list/summarize) + role/command base.

Map tier tierForScore

≥85 → premium · ≥30 → standard · else → cheap. Pipeline stage thì PIN model tường minh per role, không auto-route.

Borderline judge score 60-80

Gọi Haiku cheap chấm complexity 1-10 → ≥7 upgrade, ≤4 downgrade. Judge lỗi → giữ heuristic (không block). Cost judge ≈ $0.0001.

Budget downgrade guardrail

Remaining < 5% → force cheap; < 20% → downgrade 1 tier. Audit model.routed {score, tier, model, judged, budgetDowngraded}.

Call + Fallback LiteLLM

POST qua LiteLLM (OpenAI-compatible). Primary 5xx/429/timeout → retry 1 lần trên fallback alias → audit model.fallback. 4xx/auth = terminal. Cost đọc từ header x-litellm-response-cost.