NPC System
Overview
The NPC (Non-Player Character) System in PadawanForge provides a robust framework for creating, managing, and interacting with AI-driven characters. This system is designed to support dynamic conversations, personality-driven responses, and seamless integration with multiple AI providers and external services.
NPC Attribute Outline
The NPC system uses a streamlined set of attributes to define character behavior and capabilities. This section provides a comprehensive overview of all NPC attributes and their purposes.
Core Identity Attributes
Basic Information
name(string, required): The NPC’s display namedescription(string): Brief description of the NPC’s role and purposesystem_prompt(string, required): Core AI prompt that defines the NPC’s behavior and knowledgepersonality(string): Character personality type with predefined optionsfriendly- Friendly & Approachableformal- Formal & Professionalcasual- Casual & Relaxedplayful- Playful & Energeticwise- Wise & Philosophicalenthusiastic- Enthusiastic & Motivating
Visual & Display
avatar(string): Avatar image URL or emoji identifierlevel(integer, default: 1): NPC progression level (all new NPCs start at level 1)
AI Configuration Attributes
Provider Settings
ai_provider(string, default: ‘local’): AI service providerlocal- Cloudflare Workers AI (built into worker, recommended)openai- OpenAI API (requires API key)anthropic- Claude API (requires API key)google- Google AI (requires API key)
ai_model(string, default: ‘@cf/meta/llama-3.1-8b-instruct’): Specific AI model identifiertemperature(float, default: 0.7): Response creativity (0.0 = deterministic, 1.0 = creative)max_tokens(integer, default: 1000): Maximum response length
Behavior Settings
enable_conversation_memory(boolean, default: true): Remember previous interactionsenable_personality_responses(boolean, default: true): Use personality traits in responsespersonality_traits(string): Additional detailed personality characteristics
Advanced Configuration Attributes
CoSTAR Configuration System
advanced_configuration(JSON): Embedded CoSTAR-structured configuration for advanced NPC behavior- Contains: context, objective, style, tone, audience, response settings
- Stored either embedded in NPC record or in separate
npc_configurationstable - Used for sophisticated AI prompt engineering and personality customization
Categorization
category_id(integer): Reference to NPC category for organizationsubcategory(string): Subcategory for detailed organizationexpertise_areas(JSON): Array of expertise domainsdifficulty_level(string): Target audience difficultybeginner- New learnersintermediate- Some experienceadvanced- Experienced usersexpert- Advanced users
tags(JSON): Searchable tags for discovery
Visibility & Status
is_featured(boolean, default: false): Featured NPC for promotionis_active(boolean, default: true): NPC availability statusis_public(boolean, default: false): Public visibility
Bot Integration Attributes
External Platform Support
bot_token(string): Discord/Slack bot integration tokenbot_config(JSON): Bot-specific configuration settingsbot_channels(JSON): Allowed channels for bot operationbot_permissions(JSON): Bot permission settingsis_bot_enabled(boolean, default: false): Enable external platform integration
Analytics & Performance Attributes
Interaction Tracking
interaction_count(integer, default: 0): Total number of interactionstotal_interactions(integer, default: 0): Comprehensive interaction countaverage_response_time(float, default: 0): Average response time in millisecondssuccess_rate(float, default: 0): Interaction success percentageperformance_score(float, default: 0): Overall performance rating
Timestamps
created_at(timestamp): NPC creation dateupdated_at(timestamp): Last modification datelast_interaction_at(timestamp): Most recent interaction
Metadata Attributes
Ownership & Permissions
created_by(string): Player UUID who created the NPCcreated_at(timestamp): Creation timestampupdated_at(timestamp): Last update timestamp
Advanced Features
ai_provider_config(JSON): Provider-specific configurationcustom_functions(JSON): Custom function definitionsfunction_calling_enabled(boolean, default: false): Enable custom function calls
Default Values Summary
const NPC_DEFAULTS = {
level: 1, // All NPCs start at level 1
ai_provider: 'local', // Cloudflare Workers AI
ai_model: '@cf/meta/llama-3.1-8b-instruct', // Default Cloudflare model
temperature: 0.7, // Balanced creativity
max_tokens: 1000, // Reasonable response length
personality: 'friendly', // Default personality
enable_conversation_memory: true, // Remember interactions
enable_personality_responses: true, // Use personality traits
personality_traits: '', // No additional traits by default
advanced_configuration: null // No advanced config by default
};
Advanced Configuration Structure
The advanced_configuration field supports the CoSTAR framework for sophisticated NPC behavior:
interface NPCAdvancedConfig {
context: string; // Domain expertise and background knowledge
objective: string; // Primary teaching/interaction goal
style: string; // Communication approach and methods
tone: string; // Personality characteristics and emotional style
audience: string; // Target learner profile and demographics
response: {
encouragement: 'high' | 'medium' | 'low'; // Level of positive reinforcement
correction: 'gentle' | 'direct' | 'socratic'; // How to handle mistakes
explanation: 'detailed' | 'concise' | 'analogical'; // Explanation style
frequency: 'frequent' | 'moderate' | 'minimal'; // Response frequency
};
}
Attribute Usage Guidelines
Required Fields
name: Must be provided for all NPCssystem_prompt: Essential for AI behavior definition
Recommended Fields
description: Helps users understand NPC purposepersonality: Defines character behavior stylecategory_id: Enables proper organization and discovery
Optional Fields
personality_traits: For detailed character customizationavatar: Visual identificationtags: Enhanced discoverability
Advanced Fields
advanced_configuration: CoSTAR-structured configuration for sophisticated behaviorai_provider_config: For custom AI provider settingsbot_config: For external platform integrationcustom_functions: For specialized functionality
Form Simplification Benefits
The streamlined NPC form provides several key benefits:
- Reduced Complexity: Eliminated overlapping fields (
response_stylevspersonality) - Consistent Defaults: Centralized default values prevent inconsistencies
- Better UX: Logical field grouping and clear purposes
- Automatic Leveling: All NPCs start at level 1, no manual input required
- Provider Mapping: ‘local’ provider automatically uses Cloudflare Workers AI
- Advanced Configuration: Optional CoSTAR framework for sophisticated behavior customization
- Embedded Configuration: Advanced settings can be stored directly in NPC record or separate table
- Dynamic Form Behavior: Advanced configuration toggle replaces personality field with comprehensive CoSTAR settings
- Real-time Preview: Final system prompt preview with character count and editing capabilities
- Progressive Disclosure: Basic users see simple personality options, advanced users get full CoSTAR framework
Advanced Configuration Workflow
The NPC creation form features a sophisticated Profile Settings interface with integrated advanced configuration:
Profile Settings Tab Structure
- Tab Name: “Profile Settings” (renamed from “Basic Info” for clarity)
- Integrated Toggle: Advanced configuration toggle located within the profile tab header
- Mode Comparison: Expandable panel showing differences between basic and advanced modes
- Utility Actions: Reset, Export, Import, and Copy functions accessible via mode comparison panel
Basic Mode (Default)
- System Prompt: Standard text input with preset library and expandable preset selector
- Personality: Simple dropdown with predefined personality types (6 options with emoji indicators)
- Configuration Method: Traditional personality-based approach for quick setup
- Visual Feedback: Clear indication that advanced features are available via toggle
Advanced Mode (CoSTAR Framework Builder)
- System Prompt: Base prompt enhanced by CoSTAR framework configuration
- CoSTAR Framework Builder: Comprehensive guided interface with structured fields:
- Context (Background & Expertise): Domain knowledge and qualifications
- Objective (Teaching Goals): Primary learning outcomes and objectives
- Style (Communication Method): Teaching patterns and interaction approaches
- Tone (Personality & Emotion): Emotional characteristics and demeanor
- Audience (Target Learners): Learner profile and demographics
- Response Behavior Settings: Four configurable response patterns:
- Encouragement Level: High/Medium/Low with detailed descriptions
- Correction Style: Gentle/Direct/Socratic with behavioral explanations
- Explanation Style: Detailed/Concise/Analogical with method descriptions
- Response Frequency: Frequent/Moderate/Minimal with engagement patterns
Enhanced User Experience Features
- Progressive Disclosure: Basic users see simple options, advanced users get comprehensive controls
- Guided Configuration: Each CoSTAR field includes contextual hints and examples
- Real-time Feedback: Live character count and system prompt preview
- Mode Toggle Integration: Seamless switching between personality and CoSTAR modes
- Utility Integration: Export, import, reset, and copy functions for configuration management
Advanced Configuration Architecture
- Dual Storage Support: Configuration stored either embedded in NPC record or separate
npc_configurationstable - Structured Framework: CoSTAR methodology ensures comprehensive prompt engineering
- Backward Compatibility: Basic personality settings still supported for existing NPCs
- Dynamic System Prompt: Final prompt automatically generated from CoSTAR configuration
Profile Settings Navigation
- Single Tab Interface: All profile-related settings consolidated in one location
- Contextual Help: Mode comparison panel explains differences and capabilities
- Keyboard Shortcuts: Alt+A (toggle), Alt+R (reset), Alt+E (export), Alt+C (copy)
- Configuration Management: Import/export functionality for sharing and backup
Database Schema Alignment
The NPC attributes align with the database schema defined in migrations/0003_npc_system.sql and the advanced configuration system in migrations/0010_npc_configurations.sql:
Main NPCs Table
CREATE TABLE npcs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL, -- Required
description TEXT, -- Optional
system_prompt TEXT NOT NULL, -- Required
personality TEXT, -- Personality type
avatar TEXT, -- Visual identifier
level INTEGER DEFAULT 1, -- Always level 1 for new NPCs
-- AI Provider settings
ai_provider TEXT DEFAULT 'local' CHECK (ai_provider IN ('openai', 'anthropic', 'google', 'local')),
ai_model TEXT DEFAULT '@cf/meta/llama-3.1-8b-instruct',
advanced_configuration TEXT, -- JSON: Embedded CoSTAR configuration
-- ... additional fields
);
Advanced Configuration Table
CREATE TABLE npc_configurations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
npc_id INTEGER NOT NULL,
name TEXT NOT NULL,
context TEXT NOT NULL, -- Domain expertise and background
objective TEXT NOT NULL, -- Primary teaching goal
style TEXT NOT NULL, -- Communication approach
tone TEXT NOT NULL, -- Personality characteristics
audience TEXT NOT NULL, -- Target learner profile
response_settings TEXT NOT NULL, -- JSON for response configuration
UNIQUE(npc_id), -- One configuration per NPC
FOREIGN KEY (npc_id) REFERENCES npcs(id) ON DELETE CASCADE
);
This dual-approach architecture supports both embedded configuration (stored in the main NPC record) and separate configuration management (stored in dedicated table), providing flexibility for different use cases and administration needs.
CoSTAR Prompt Engineering for NPCs
The NPC system uses the CoSTAR prompt engineering framework to structure all LLM interactions. This ensures prompts are clear, actionable, and context-rich, improving both reliability and customizability.
CoSTAR Structure:
- Context: NPC background, player state, conversation history, and knowledge base snippets (from R2)
- Objectives: What the NPC should achieve in this interaction (e.g., answer a question, advance a quest)
- Steps: How the LLM should process the input (e.g., retrieve context, consult knowledge, generate reply)
- Tools: Which AI provider/model to use (e.g., Cloudflare Workers AI), and access to R2 or MCP
- Actions: The specific reply or operation to perform
- Results: What a successful response looks like (e.g., in-character, accurate, context-aware)
Example CoSTAR Prompt:
Context: You are "Einstein", an AI tutor with the following characteristics:
[system_prompt]
Your Core Identity:
- Name: Einstein
- Personality: Curious and analytical, loves explaining complex concepts simply
- Response Style: friendly
- Target Audience: Level 1 learners
- Memory Enabled: Yes
Current Interaction:
- Player: Student (Level 1)
- Message: "Can you explain the theory of relativity in simple terms?"
- Conversation Type: Individual private chat
Recent Conversation History:
[previous messages if available]
Objectives:
- Respond in character as Einstein
- Maintain your personality: Curious and analytical
- Provide educational value when appropriate
- Use your friendly communication style
- Keep responses engaging but concise (1-3 sentences)
Steps:
1. ANALYZE the player's message for intent and learning opportunities
2. CONSIDER your personality and how Einstein would naturally respond
3. REVIEW conversation history for context and continuity
4. DETERMINE if this requires teaching, guidance, or casual interaction
5. CRAFT a response that balances personality with educational value
6. ENSURE the response fits your friendly style
Tools:
- Your expertise as Einstein
- Cloudflare Workers AI (@cf/meta/llama-3.1-8b-instruct)
- Conversation memory: Available
- Knowledge base: Available
Actions:
Generate a natural, engaging response that:
- Stays fully in character as Einstein
- Uses your personality traits: Curious and analytical
- Applies your friendly communication style
- Provides gentle guidance or teaching when appropriate
- Maintains conversation flow and engagement
- Avoids breaking character or mentioning you're an AI
Results:
The player receives a helpful, in-character response that feels natural and educational.
Cloudflare Workers AI Integration
The AI Adapter supports Cloudflare Workers AI models (such as @cf/meta/llama-3.1-8b-instruct and @hf/thebloke/neural-chat-7b-v3-1-awq). Prompts are sent in the CoSTAR format, and knowledge from R2 can be injected as context. This enables scalable, cost-effective, and privacy-friendly AI for NPCs.
Supported Models:
@cf/meta/llama-3.1-8b-instruct- Primary model for general conversations@cf/meta/llama-3.1-70b-instruct- High-performance model for complex reasoning@hf/thebloke/neural-chat-7b-v3-1-awq- Efficient model for cost-sensitive applications
Player–NPC Interaction Modes
Players can interact with NPCs in two main ways:
1. Individual Chat
- Players can initiate a private, one-on-one chat with any NPC.
- The chat interface sends messages directly to the NPC, and the conversation is private.
- The CoSTAR prompt context includes only the player and NPC’s conversation history and knowledge base.
- Conversation memory is maintained across sessions if enabled.
2. Game Lobby Chat
- Players can add one or more NPCs to a multiplayer game lobby.
- NPCs participate in group conversations and can be addressed using
@NPCNamein chat. - The CoSTAR prompt context includes the recent lobby conversation and all participants, allowing NPCs to respond in a group-aware manner.
- NPCs can be dynamically added or removed from the lobby.
Example Use Cases:
- A player chats privately with an NPC for tutoring or story progression.
- A group of players adds an NPC to their lobby for collaborative gameplay, quest guidance, or group challenges.
Technical Note:
- The system dynamically adjusts the CoSTAR prompt’s context and objectives depending on whether the interaction is individual or in a group lobby.
Role-Based NPC Creation
The NPC system implements role-based access control for NPC creation:
- Guest (Level 0): Cannot create NPCs
- Padawan (Level 1): Can create up to 3 NPCs (all start at Level 1)
- Game Master (Level 2+): Unlimited NPC creation
This ensures appropriate resource management while allowing experienced users to create rich NPC ecosystems.
NPC Level System
- All new NPCs start at Level 1 by default
- NPCs can level up based on interaction count and performance
- Higher-level NPCs may have access to more advanced AI models and features
Knowledge Base Management
NPCs can be equipped with custom knowledge bases stored in Cloudflare R2:
File Management
- Upload: Support for text, PDF, and other document formats
- Processing: Automatic content extraction and summarization
- Organization: Categorization and tagging for easy retrieval
- Security: Role-based access control for sensitive content
Content Types
- Raw Text: Direct text content for immediate use
- Summaries: AI-generated content summaries for quick reference
- Keywords: Extracted key terms and concepts
- Embeddings: Vector representations for semantic search
- Metadata: File properties and processing information
AutoRAG Integration (Planned v1.4.0)
A future enhancement will integrate Cloudflare AutoRAG (AI Search) for semantic retrieval:
- Per-NPC Knowledge Bases: Each NPC can have a dedicated AutoRAG instance
- Semantic Search: Vector-based retrieval for contextually relevant information
- Automatic Indexing: Cloudflare manages embeddings and vector storage
- Grounded Responses: Reduce hallucinations by retrieving factual context
- Query Rewriting: Intelligent query improvement for better results
Proposed Architecture:
R2 Bucket (Knowledge) → AutoRAG Instance → NPC Chat Request
↓ ↓ ↓
Documents uploaded Auto-indexed with Retrieve relevant context
embeddings Inject into CoSTAR prompt
API Usage:
// Retrieve context for NPC response
const context = await env.AI.autorag(npc.knowledge_base_name).search({
query: playerMessage,
rewrite_query: true,
max_results: 5
});
For detailed implementation plans, see AutoRAG Knowledge Bases.
Statement Generation System
The NPC system includes an AI-powered statement generation system for educational content:
Features
- Topic-Based Generation: Create statements for specific subjects (Physics, History, etc.)
- Difficulty Levels: Beginner, intermediate, and expert content
- Quality Scoring: Automated quality assessment and validation
- Caching: Efficient reuse of generated content
- Usage Analytics: Track performance and engagement metrics
Generation Process
- Input: Topic, difficulty level, and statement count
- Processing: AI generates educational true/false statements
- Validation: Quality scoring and content review
- Storage: Cached in statement pools for reuse
- Delivery: Integrated into NPC interactions and games
Example Use Cases
- Dynamic NPCs: Create AI-powered characters that adapt to player choices and game events
- Cross-Platform Bots: Deploy NPCs that interact with users on both web and external chat platforms
- Knowledge-Driven Dialogue: Equip NPCs with custom knowledge bases stored in R2 for deep, context-aware conversations
- Educational Tutoring: Use NPCs as personalized tutors with subject-specific expertise
- Interactive Storytelling: Create narrative NPCs that guide players through immersive experiences
Related Documentation
Implementation Status
Current Implementation
The NPC system is actively developed with core functionality implemented and advanced features in progress:
✅ Implemented Features:
- Core NPC Management: Complete CRUD operations with role-based permissions
- Local AI Provider: Default provider maps to Cloudflare Workers AI (built into worker)
- Conversation System: Individual chat with conversation memory
- Database Schema: Comprehensive NPC storage with categories and analytics
- API Endpoints: Basic NPC management and chat functionality
- Role-Based Access: Creation limits and permissions enforced
- Knowledge Base Infrastructure: File storage and processing framework
- Provider Mapping: ‘local’ provider automatically uses Cloudflare Workers AI
- Personality System: NPC character configuration and behavior
- Profile Settings Interface: Enhanced NPC form modal with integrated advanced configuration
- CoSTAR Framework Builder: Guided interface for sophisticated AI prompt engineering
- Progressive Disclosure: Seamless switching between basic and advanced configuration modes
- Configuration Management: Export, import, reset, and copy functionality for NPC configurations
🔄 In Progress:
- Group Chat Functionality: NPCs in lobby conversations
- Statement Generation: AI-powered educational content creation
- Admin UI Enhancements: Advanced bulk operations and management tools
❌ Planned Features:
- AutoRAG Knowledge Bases (v1.4.0): Semantic retrieval for NPC knowledge using Cloudflare AI Search
- Real-time Activity Feeds: Live NPC interaction tracking
- Advanced Analytics: Detailed performance insights
- Multi-Platform Bot Integration: Discord, Telegram, Slack support
- Knowledge Base Streaming: Real-time content updates
Technical Notes
Database Schema:
- Uses
ai_providercolumn for provider storage with constraint:('openai', 'anthropic', 'google', 'local') - ‘local’ provider maps to Cloudflare Workers AI (built into the worker)
- Knowledge files and statement pools infrastructure is in place
- Personality field for NPC character configuration
AI Provider Support:
- Local (Cloudflare Workers AI): Default provider - maps to Cloudflare Workers AI built into the worker
- Other Providers: OpenAI, Anthropic, Google, and other external providers supported
- Custom Providers: Any custom AI provider can be configured
- Model Selection: Automatic model selection based on use case and provider
Development Roadmap
Short Term (v1.2.6):
- ✅ Implement CoSTAR prompt engineering framework (Profile Settings integration complete)
- ✅ Add advanced admin configuration UI (CoSTAR Framework Builder implemented)
- ✅ Enhance Cloudflare AI model selection and optimization (Enhanced AI Configuration tab complete)
Medium Term (v1.3.0):
- Full group chat functionality with NPCs
- Statement generation system
- Real-time activity tracking
Long Term (v1.4.0):
- AutoRAG Knowledge Bases: Cloudflare AI Search integration for semantic retrieval
- Multi-platform bot integration
- Advanced analytics and insights
- Knowledge base streaming and real-time updates
This section reflects the current implementation status as of v1.2.6 with ongoing development.
Internal Dependencies
The NPC system integrates with multiple internal components and services throughout the PadawanForge codebase. This section provides a comprehensive reference for developers working with or extending the NPC system.
Core Services & Libraries
NpcManager
- File:
src/lib/services/NpcManager.ts - Implementation: Core CRUD operations for NPC management, interaction handling, conversation history
- Integration: Requires D1Database binding, used by API endpoints and admin components
- Rules: Must validate role permissions before creation/deletion, enforces NPC creation limits per user role
NpcAgent
- File:
src/lib/services/NpcAgent.ts - Implementation: CoSTAR prompt engineering framework, AI statement generation, conversation handling
- Integration: Depends on AIService, connects to Cloudflare Workers AI, integrates with database storage
- Rules: Fallback to template generation when AI unavailable, requires NPC configuration, handles AI provider failures gracefully
AIService
- File:
src/lib/services/AIService.ts - Implementation: AI provider abstraction layer, request/response handling, token management
- Integration: Used by NpcAgent, supports multiple AI providers, integrates with Cloudflare AI binding
- Rules: Provider-agnostic interface, handles rate limiting, manages API key validation
Database Layer
Core NPC Schema
- File:
migrations/0003_npc_system.sql - Implementation: Complete NPC system tables with AI providers, conversations, categorization
- Tables:
npcs,npc_interactions,npc_conversations,npc_categories,npc_learning_data,npc_analytics,ai_providers - Integration: Foundation for all NPC operations, includes performance indexes and triggers
- Rules: Foreign key constraints to players table, automatic timestamp updates, interaction counting
Storage Infrastructure
- File:
migrations/0007_npc_storage.sql - Implementation: Knowledge files, statement pools, conversation memory storage
- Tables:
npc_knowledge_files,npc_knowledge_data,statement_pools,statement_usage,npc_conversation_memory - Integration: R2 storage integration for knowledge files, caching system for AI-generated content
- Rules: Automatic cleanup of expired pools, usage tracking, file processing status management
API Endpoints
NPC Management API
- File:
src/pages/api/npcs/index.ts - Implementation: GET/POST endpoints for NPC listing and creation
- Integration: Uses NpcManager, requires authentication, role-based access control
- Rules: Validates user permissions, enforces creation limits, sanitizes input data
Individual NPC API
- File:
src/pages/api/npcs/[id].ts - Implementation: GET/PUT/DELETE for specific NPC operations
- Integration: NpcManager integration, ownership validation
- Rules: Only creators or admins can modify NPCs, soft delete preservation
NPC Chat API
- File:
src/pages/api/npcs/[id]/chat.ts - Implementation: Real-time chat interface with NPCs
- Integration: NpcAgent for response generation, conversation history tracking
- Rules: Rate limiting, conversation memory management, error handling with fallbacks
Statement Generation API
- File:
src/pages/api/npcs/[id]/statements/generate.ts - Implementation: AI-powered educational statement generation
- Integration: NpcAgent integration, statement pool caching
- Rules: Topic validation, difficulty level enforcement, quality scoring
Knowledge Management APIs
- File:
src/pages/api/npcs/[id]/knowledge-files.ts&src/pages/api/npcs/[id]/knowledge-files/[fileId].ts - Implementation: File upload, processing, and retrieval for NPC knowledge bases
- Integration: R2 storage binding, content processing pipeline
- Rules: File type validation, size limits, processing status tracking
Configuration API
- File:
src/pages/api/npcs/[id]/configure.ts - Implementation: NPC personality and behavior configuration
- Integration: NpcAgent configuration management, preset system
- Rules: Validates configuration schema, maintains backward compatibility
UI Components
Admin Dashboard Components
-
File:
src/components/admin/npcs-table.tsx -
Implementation: Tabular display of NPCs with management actions
-
Integration: Uses NpcManager API, role-based action visibility
-
Rules: Respects user permissions, real-time updates, pagination support
-
File:
src/components/admin/lazy-npcs-dashboard.tsx -
Implementation: Lazy-loaded NPC management dashboard
-
Integration: Performance optimization for large NPC lists
-
Rules: Skeleton loading states, error boundaries, responsive design
-
File:
src/components/admin/admin-npc-chat.tsx -
Implementation: Admin interface for testing NPC conversations
-
Integration: WebSocket connection for real-time chat
-
Rules: Admin-only access, conversation logging, debug information display
NPC Creation & Management
-
File:
src/components/shared/npc-form-modal.tsx -
Implementation: Comprehensive NPC creation and editing modal with Profile Settings interface
-
Integration: Form validation, preset selector, AI provider configuration, CoSTAR framework builder
-
Features: Integrated advanced mode toggle, mode comparison panel, configuration management tools
-
Rules: Role-based field visibility, validation schema enforcement, real-time preview, progressive disclosure
-
Tab Structure: Profile Settings (with integrated toggle), AI Configuration, Testing
-
File:
src/components/admin/npc-form-modal.tsx -
Implementation: Admin-specific NPC form with advanced options
-
Integration: Extended configuration options, system-level settings
-
Rules: Admin-only features, bulk operations support, advanced validation
-
File:
src/components/shared/npc-preset-selector.tsx -
Implementation: Personality preset selection interface
-
Integration: Preset API integration, dynamic configuration loading
-
Rules: Preset validation, custom personality support, UI consistency
Chat & Interaction Components
-
File:
src/components/game/npc-chat-modal.tsx -
Implementation: Player-facing NPC chat interface
-
Integration: Real-time messaging, conversation history, typing indicators
-
Rules: Message rate limiting, profanity filtering, conversation persistence
-
File:
src/components/game/npc-character-card.tsx -
Implementation: NPC display card with interaction options
-
Integration: Avatar display, quick stats, action buttons
-
Rules: Responsive design, accessibility compliance, interaction state feedback
-
File:
src/components/game/npc-manager.tsx -
Implementation: In-game NPC management interface
-
Integration: Game state integration, real-time updates
-
Rules: Game context awareness, performance optimization, mobile-friendly
Specialized Components
-
File:
src/components/home/lazy-npc-preview.tsx -
Implementation: Homepage NPC preview with lazy loading
-
Integration: Performance-optimized display, featured NPC rotation
-
Rules: SEO optimization, loading state handling, fallback content
-
File:
src/components/tutorial/demos/NPCChatDemo.tsx -
Implementation: Interactive demo for NPC chat functionality
-
Integration: Demo data, simulated interactions, tutorial progression
-
Rules: Educational focus, guided interaction flow, reset functionality
Page Components
NPC Management Pages
-
File:
src/pages/npcs.astro -
Implementation: Public NPC browsing and interaction page
-
Integration: Server-side rendering, NPC listing, search functionality
-
Rules: SEO optimization, mobile responsiveness, performance caching
-
File:
src/pages/admin/npcs.astro -
Implementation: Admin NPC management dashboard
-
Integration: Role-based access, comprehensive management tools
-
Rules: Admin authentication required, audit logging, bulk operations
Documentation Pages
- File:
src/pages/documentation/npcs.astro&src/pages/documentation/api/npcs.astro - Implementation: NPC system documentation and API reference
- Integration: Static content generation, code examples
- Rules: Documentation versioning, example validation, accessibility standards
Configuration & Infrastructure
Cloudflare Configuration
- File:
wrangler.jsonc - Implementation: Cloudflare Workers configuration with NPC-required bindings
- Bindings: D1 database, R2 bucket, AI service, Durable Objects, KV storage
- Integration: Essential for NPC system operation, defines resource limits
- Rules: Environment-specific configurations, security settings, performance optimization
Build Configuration
- File:
astro.config.mjs - Implementation: Astro framework configuration for NPC component integration
- Integration: React component support, Tailwind styling, Cloudflare adapter
- Rules: Production optimization, SSR configuration, module resolution
Constants & Utilities
-
File:
src/lib/constants.ts -
Implementation: NPC-related constants and configuration values
-
Integration: Shared across all NPC components, centralized configuration
-
Rules: Type safety, environment-aware values, backward compatibility
-
File:
src/lib/utils/permissions.ts -
Implementation: Role-based access control for NPC operations
-
Integration: Used by all NPC components and API endpoints
-
Rules: Hierarchical permission system, audit trail requirements, security enforcement
Durable Objects Integration
ChatLobby Durable Object
- File:
src/durable-objects/ChatLobby.ts - Implementation: Real-time chat management with NPC integration
- Integration: WebSocket handling, NPC message routing, conversation state
- Rules: Message persistence, rate limiting, error recovery, scalability considerations
Workflow Integration
Player Workflow
- File:
src/workflows/player_workflow.ts - Implementation: Player lifecycle management affecting NPC interactions
- Integration: NPC creation limits, interaction tracking, progression systems
- Rules: Workflow state consistency, error handling, performance monitoring
Integration Rules Summary
- Authentication: All NPC operations require valid session tokens
- Authorization: Role-based access control enforced at API and UI levels
- Data Validation: Strict input validation using Zod schemas
- Error Handling: Graceful fallbacks for AI provider failures
- Performance: Lazy loading, caching, and pagination for scalability
- Security: Input sanitization, SQL injection prevention, rate limiting
- Consistency: Standardized error responses and status codes
- Monitoring: Comprehensive logging and analytics integration
- Accessibility: WCAG compliance across all UI components
- Internationalization: Support for multiple languages in NPC responses