BOSS Agent Chat Architecture
Document Version: 1.0.0 Last Updated: January 1, 2026 Status: π PROTECTED - Consult before ANY chat-related changes
β οΈ CRITICAL: READ BEFORE MAKING CHANGES
This document defines the production-critical architecture for the Boss Agent chat system. You MUST consult this document before making ANY changes to:
- Frontend chat components (
BOSSChat.tsx,BOSSChatEnhanced.tsx) - Chat hooks (
useBOSS.ts,useOrchestration.ts,useNervousSystem.ts) - API routes (
app/api/boss/chat/route.ts) - Boss Agent chat endpoints (
boss_agent_adk_production.py) - Type definitions (
lib/api/types.ts,lib/api/boss.ts)
Failure to follow this architecture WILL break production chat functionality.
Table of Contents
- Architecture Overview
- Data Flow Diagram
- Component Hierarchy
- Hook Interfaces
- API Endpoints
- Type Definitions
- Response Format Contract
- Integration Points
- Common Pitfalls
- Change Checklist
- Testing Protocol
1. Architecture Overview
The Boss Agent chat system uses a layered architecture with clear separation of concerns:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PRESENTATION LAYER β
β βββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββ β
β β BOSSChat.tsx β β BOSSChatEnhanced.tsx β β
β β (Primary Chat) β β (Enhanced with Nervous System) β β
β ββββββββββ¬βββββββββ ββββββββββββββββββββ¬βββββββββββββββββββ β
βββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββ
β β
βββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββ
β HOOKS LAYER β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β useChat() - PRIMARY β β
β β Returns: messages, isStreaming, sendMessage, etc. β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββ β
β β useChatMutation β β useMOACollabor. β βuseNervousSys β β
β β (Legacy) β β (MOA Debate) β β (KG/SRPVDAL) β β
β ββββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββ
β API ROUTE LAYER β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β /api/boss/chat/route.ts β β
β β - Receives: { message, conversationId, context } β β
β β - Forwards to: Boss Agent /process β β
β β - Returns: { id, response, content, metadata, error } β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββ
β BOSS AGENT (Cloud Run) β
β URL: https://boss-agent-adk-698171499447.us-central1.run.app β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β /process endpoint β β
β β - SRPVDAL Pipeline (Sense β Reason β Decide β Act β Learn)β β
β β - MOE Routing / MOA Collaboration β β
β β - Returns: ProcessResponse β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
2. Data Flow Diagram
Request Flow (User β Backend)
User types message
β
βΌ
βββββββββββββββββββββββββββββββββββββββββ
β BOSSChat.tsx β
β sendMessage(input, options) β
βββββββββββββββββββββ¬ββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββ
β useChat() Hook (useBOSS.ts) β
β β
β 1. Add user message to state β
β 2. Set isStreaming = true β
β 3. Create AbortController β
β 4. POST to /api/boss/chat β
βββββββββββββββββββββ¬ββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββ
β /api/boss/chat/route.ts β
β β
β 1. Parse request body β
β 2. Extract message from various keys β
β 3. Forward to Boss Agent /process β
β 4. Normalize response format β
βββββββββββββββββββββ¬ββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββ
β Boss Agent ADK /process β
β β
β 1. SRPVDAL Pipeline execution β
β 2. Claude Opus 4.6 processing β
β 3. Cell orchestration β
β 4. Return ProcessResponse β
βββββββββββββββββββββββββββββββββββββββββ
Response Flow (Backend β User)
Boss Agent returns ProcessResponse
β
βΌ
βββββββββββββββββββββββββββββββββββββββββ
β /api/boss/chat/route.ts β
β β
β Normalize to: β
β { β
β id: data.message_id || Date.now(), β
β response: data.content || data... β
β content: data.content, β
β metadata: data.metadata, β
β error: false β
β } β
βββββββββββββββββββββ¬ββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββ
β useChat() Hook β
β β
β Extract content: β
β data.response || β
β data.content || β
β data.message?.content || β
β 'No response received' β
β β
β Add assistant message to state β
β Set isStreaming = false β
βββββββββββββββββββββ¬ββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββ
β BOSSChat.tsx β
β β
β Render messages array β
β Show response to user β
βββββββββββββββββββββββββββββββββββββββββ
3. Component Hierarchy
Primary Chat Components
components/chat/
βββ BOSSChat.tsx # PRIMARY - Full-featured chat
β βββ Uses: useChat() # Comprehensive state management
β βββ Uses: useAgents() # Agent list
β βββ Uses: useCellRegistry() # Cell registry
β βββ Uses: useNervousSystem() # KG/SRPVDAL context
β βββ Features:
β βββ Orchestration mode selector
β βββ MOA debate visualizer
β βββ Nervous system panel
β βββ Pending approvals view
β βββ Streaming response display
β
βββ BOSSChatEnhanced.tsx # ALTERNATIVE - Different UX
β βββ Uses: useChatMutation() # Simple mutation
β βββ Uses: useMOACollaboration() # MOA streaming
β βββ Uses: useCellRegistry() # Cell registry
β βββ Uses: useNervousSystemActivity() # Activity monitor
β
βββ OrchestrationModeSelector.tsx # Mode tabs (Auto/MOE/MOA/Direct)
βββ MOADebateVisualizer.tsx # Debate rounds visualization
Supporting Components
components/
βββ NervousSystemPanel # Embedded in BOSSChat
β βββ KG Context (WHAT)
β βββ SRPVDAL Procedures (HOW)
β βββ Causal Analysis (WHY)
β βββ Active Cells
β
βββ MessageBubble # Chat message display
βββ StreamingResponse # Typing indicator + partial response
βββ PendingApprovalsView # Action approval UI
4. Hook Interfaces
useChat() - PRIMARY HOOK
Location: hooks/api/useBOSS.ts
Purpose: Comprehensive chat state management for BOSSChat.tsx
interface UseChatOptions {
onAgentStart?: (agentId: string, agentName: string, cellId: string) => void;
onCellInvoked?: (cellId: string, endpoint: string) => void;
onMOAContribution?: (contribution: AgentContribution) => void;
onApprovalRequired?: (approval: ApprovalRequest) => void;
}
interface UseChatReturn {
// Chat state
messages: ChatMessage[]; // Full message history
currentResponse: string; // Streaming response text
isStreaming: boolean; // Is currently processing
activeAgent: string | null; // Currently active agent name
activeCells: string[]; // Cells being used
error: { message: string } | null; // Error state
// MOA collaboration
moaContributions: AgentContribution[];
currentMOARound: number;
// Approvals
pendingApprovals: ApprovalRequest[];
// Actions
sendMessage: (content: string, options?: ChatOptions) => Promise<void>;
stopStreaming: () => void;
clearMessages: () => void;
approveAction: (approvalId: string) => Promise<void>;
rejectAction: (approvalId: string, reason?: string) => Promise<void>;
// Metadata
conversationId: string;
}
CRITICAL: This hook calls /api/boss/chat (Next.js route), NOT the Boss Agent directly.
useChatMutation() - LEGACY HOOK
Location: hooks/api/useBOSS.ts
Purpose: Simple mutation for BOSSChatEnhanced.tsx
// Returns TanStack Query mutation
const mutation = useChatMutation();
// Usage:
const result = await mutation.mutateAsync({
message: string,
conversationId?: string,
options?: ChatOptions
});
// Result is ProcessResponse type
CRITICAL: Calls bossApi.chat.chat() which hits /api/v1/chat on Boss Agent.
useNervousSystem() - CONTEXT HOOK
Location: hooks/api/useNervousSystem.ts
interface UseNervousSystemReturn {
kgContext: KGContext | null;
srpvdalProcedure: SRPVDALProcedure | null;
srpvdalRouting: SRPVDALRoutingDecision | null;
causalAnalysis: RootCauseAnalysis | null;
consultation: NervousSystemConsultation | null;
isLoadingKG: boolean;
isLoadingSRPVDAL: boolean;
isLoadingCausal: boolean;
isLoadingConsultation: boolean;
queryKG: (query: string) => Promise<KGContext>;
queryProcedure: (task: string) => Promise<SRPVDALProcedure | null>;
queryRouting: (query: string) => Promise<SRPVDALRoutingDecision>;
analyzeRootCause: (symptom: string) => Promise<RootCauseAnalysis>;
consult: (query: string) => Promise<NervousSystemConsultation>;
}
useCellRegistry() - REGISTRY HOOK
Location: hooks/api/useBOSS.ts
// Returns:
{
data: {
cells: AgentInfo[]; // Array of cells
agents: AgentInfo[]; // Array of agents
orchestrators: AgentInfo[]; // Array of orchestrators
lastDiscovery: string; // Timestamp
} | undefined;
isLoading: boolean;
error: Error | null;
}
β οΈ COMMON PITFALL: cellRegistry is an OBJECT, not an array. Access cells via cellRegistry?.cells?.map().
5. API Endpoints
Frontend Routes (Next.js)
| Route | Method | Purpose | Forwards To |
|---|---|---|---|
/api/boss/chat |
POST | Main chat endpoint | Boss Agent /process |
/api/boss/approve |
POST | Approval actions | Boss Agent /approve |
Boss Agent Endpoints
| Endpoint | Method | Purpose |
|---|---|---|
/process |
POST | Main chat (SRPVDAL pipeline) |
/api/v1/chat |
POST | API v1 chat endpoint |
/api/v1/chat/stream |
POST | Streaming chat (SSE) |
/health |
GET | Health check |
/status |
GET | Detailed status |
/agents |
GET | List agents |
/registry |
GET | Full cell registry |
API Client Structure (lib/api/boss.ts)
bossApi = {
health: {
getHealth(): Promise<HealthResponse>;
getStatus(): Promise<StatusResponse>;
getMetrics(): Promise<Record<string, unknown>>;
},
chat: {
process(request: ChatRequest): Promise<ProcessResponse>;
chat(request: ChatRequest): Promise<ProcessResponse>;
coordinateTasks(tasks: Task[]): Promise<CoordinationResponse>;
},
agents: {
list(): Promise<AgentInfo[]>;
get(id: string): Promise<AgentInfo>;
execute(id: string, task: string): Promise<ExecutionResult>;
getRegistry(): Promise<Registry>;
},
sessions: { /* ... */ },
conversations: { /* ... */ },
kg: { /* ... */ },
// ... more namespaces
}
6. Type Definitions
ChatRequest (Frontend β Backend)
// lib/api/boss.ts
interface ChatRequest {
message: string;
conversationId?: string;
options?: ChatOptions;
}
// lib/api/types.ts (more complete)
interface ChatRequest {
message: string;
conversationId?: string;
userId?: string;
context?: Record<string, unknown>;
options?: ChatOptions;
}
ChatOptions
interface ChatOptions {
// Streaming
stream?: boolean;
maxTokens?: number;
temperature?: number;
// Orchestration
orchestration?: 'auto' | 'moe' | 'moa' | 'direct';
// MOE
forceExperts?: string[];
excludeExperts?: string[];
explainRouting?: boolean;
// MOA
moaAgents?: string[];
moaMode?: 'debate' | 'consensus' | 'pipeline' | 'parallel';
streamDebate?: boolean;
// Direct
targetAgent?: string;
// Nervous System
consultNervousSystem?: boolean;
}
ProcessResponse (Backend β Frontend)
// lib/api/boss.ts
interface ProcessResponse {
conversationId: string;
message: ChatMessage;
srpvdalCycle?: {
sense: Record<string, unknown>;
reason: Record<string, unknown>;
decide: Record<string, unknown>;
act: Record<string, unknown>;
learn: Record<string, unknown>;
cycleTime: number;
};
cellsUsed: string[];
routingExplanation?: string;
actionResults?: Record<string, unknown>[];
pendingActions?: PendingAction[];
}
ChatMessage
interface ChatMessage {
id: string;
role: 'user' | 'assistant' | 'system' | 'agent';
content: string;
timestamp: string;
metadata?: {
agentId?: string;
agentsInvoked?: string[];
taskId?: string;
confidence?: number;
citations?: Citation[];
toolCalls?: ToolCall[];
};
}
7. Response Format Contract
Next.js Route Response (/api/boss/chat)
The route MUST return this format:
{
id: string; // Message ID
response: string; // Primary response content
content?: string; // Alternative content field
metadata?: object; // Additional metadata
error: boolean; // Error flag
}
useChat() Extraction Logic
The hook extracts content in this order:
const responseContent =
data.response || // First: response field
data.content || // Second: content field
data.message?.content || // Third: nested message.content
(typeof data.message === 'string' ? data.message : 'No response received');
β οΈ CRITICAL: If you change the response format, you MUST update this extraction logic.
useChatMutation() Extraction Logic
For BOSSChatEnhanced.tsx:
// ProcessResponse structure
response = chatResult.message?.content || 'No response received.';
metadata.routedTo = chatResult.routingExplanation;
metadata.confidence = chatResult.message?.confidence;
8. Integration Points
Hook Exports (hooks/api/index.ts)
// REQUIRED exports for chat functionality
export {
useChat, // Primary chat hook
useChatMutation, // Legacy mutation hook
useProcess, // Direct process mutation
useAgents, // Agent list
useCellRegistry, // Cell registry
// ... other exports
} from './useBOSS';
export { useNervousSystem } from './useNervousSystem';
export {
useMOACollaboration,
useMOACollaborationMutation,
// ... other exports
} from './useOrchestration';
Component Imports
// BOSSChat.tsx
import { useChat, useAgents, useCellRegistry, useNervousSystem } from '@/hooks/api';
// BOSSChatEnhanced.tsx
import { useChatMutation, useCellRegistry } from '@/hooks/api';
import { useMOACollaboration } from '@/hooks/api/useOrchestration';
import { useNervousSystem, useNervousSystemActivity } from '@/hooks/api/useNervousSystem';
9. Common Pitfalls
β WRONG: Accessing cellRegistry as array
// WRONG - cellRegistry is an object
cellRegistry?.map((cell) => ...)
// CORRECT
cellRegistry?.cells?.map((cell) => ...)
β WRONG: Using wrong ChatRequest property
// WRONG - 'context' is for general data
chat.mutateAsync({ message: "hi", context: { mode: "moe" } })
// CORRECT - 'options' is for chat options
chat.mutateAsync({ message: "hi", options: { orchestration: "moe" } })
β WRONG: Accessing non-existent response properties
// WRONG - ProcessResponse doesn't have these at top level
chatResult.response
chatResult.routed_to
chatResult.confidence
// CORRECT
chatResult.message?.content
chatResult.routingExplanation
chatResult.message?.confidence
β WRONG: Using wrong useNervousSystem properties
// WRONG - These property names don't exist
const { context, procedures, isLoading } = useNervousSystem();
// CORRECT
const {
kgContext,
srpvdalProcedure,
isLoadingKG,
isLoadingSRPVDAL
} = useNervousSystem();
β WRONG: Expecting array from srpvdalProcedure
// WRONG - srpvdalProcedure is a single object
procedures.map((proc) => ...)
// CORRECT - Wrap in array if needed
(srpvdalProcedure ? [srpvdalProcedure] : []).map((proc) => ...)
β WRONG: Missing task in MOACollaborationRequest
// WRONG - task is required
moaCollaboration.startCollaboration({ query: "..." })
// CORRECT
moaCollaboration.startCollaboration({
query: "...",
task: "...", // Required!
mode: "debate"
})
10. Change Checklist
Before making ANY changes to chat functionality, verify:
Pre-Change Verification
- [ ] Read this architecture document completely
- [ ] Understand the current data flow
- [ ] Identify all affected files
- [ ] Check type definitions in
lib/api/types.tsandlib/api/boss.ts
During Development
- [ ] Maintain backward compatibility with existing response formats
- [ ] Update ALL components using changed hooks
- [ ] Update ALL hooks using changed API methods
- [ ] Keep type definitions in sync across files
- [ ] Add proper error handling
Pre-Commit Verification
- [ ] Run
npm run lint- no new errors - [ ] Run
npx tsc --noEmit- check for type errors in chat files - [ ] Test BOSSChat.tsx manually
- [ ] Test BOSSChatEnhanced.tsx manually
- [ ] Verify streaming works
- [ ] Verify error handling works
- [ ] Verify MOA collaboration works (if applicable)
Files to Check After Changes
| If you change... | Also check... |
|---|---|
useBOSS.ts hooks |
BOSSChat.tsx, BOSSChatEnhanced.tsx |
lib/api/boss.ts types |
useBOSS.ts, all chat components |
lib/api/types.ts |
useBOSS.ts, useOrchestration.ts, all chat components |
/api/boss/chat/route.ts |
useChat() extraction logic |
Boss Agent /process |
Route response normalization |
11. Testing Protocol
Manual Testing Checklist
## BOSSChat.tsx Tests
1. [ ] Send a simple message β Receive response
2. [ ] Send message in MOE mode β Expert routing works
3. [ ] Send message in MOA mode β Debate visualization shows
4. [ ] Send message in Direct mode β Routes to selected agent
5. [ ] Click Stop while streaming β Cancels request
6. [ ] Click Clear β Clears all messages
7. [ ] Nervous System panel β Shows KG context
8. [ ] Error handling β Shows error message in chat
## BOSSChatEnhanced.tsx Tests
1. [ ] Send a simple message β Receive response
2. [ ] MOA collaboration β Debate panel shows
3. [ ] Direct cell selection β Cell dropdown works
4. [ ] Settings panel β Opens and closes
5. [ ] Mode switching β Tabs work correctly
## Edge Cases
1. [ ] Empty message β Should not send
2. [ ] Network error β Shows error gracefully
3. [ ] Timeout β Shows timeout message
4. [ ] Rapid messages β Handles correctly
5. [ ] Long response β Renders properly
Automated Tests (Future)
// tests/chat/useChat.test.ts
describe('useChat hook', () => {
it('should add user message to messages array');
it('should set isStreaming true when sending');
it('should extract response from various formats');
it('should handle errors gracefully');
it('should support abort controller cancellation');
});
// tests/chat/BOSSChat.test.tsx
describe('BOSSChat component', () => {
it('should render message input');
it('should display messages');
it('should show streaming indicator');
it('should show nervous system panel');
});
Version History
| Version | Date | Changes |
|---|---|---|
| 1.0.0 | 2026-01-01 | Initial architecture documentation |
Maintainers
- Architecture Owner: Development Team
- Last Review: January 1, 2026
Quick Reference Card
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BOSS CHAT QUICK REFERENCE β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β PRIMARY HOOK: useChat() from '@/hooks/api' β
β LEGACY HOOK: useChatMutation() from '@/hooks/api' β
β β
β FRONTEND ROUTE: /api/boss/chat β Boss Agent /process β
β β
β RESPONSE FORMAT: β
β Route returns: { id, response, content, metadata, error } β
β Hook extracts: data.response || data.content || ... β
β β
β COMMON MISTAKES: β
β β cellRegistry?.map() β β cellRegistry?.cells?.map() β
β β context: { mode } β β options: { orchestration } β
β β chatResult.response β β chatResult.message?.content β
β β { context, procedures } β β { kgContext, srpvdalProcedure }β
β β
β BEFORE ANY CHANGE: Read BOSS_AGENT_CHAT_ARCHITECTURE.md β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ