F365

Friend365

Product overview

Twenty four seven AI companionship with crisis aware guardrails, designed for global users and built with privacy by default.

Always on, always safe.

Friend365 partners with OpenRouter models to deliver empathetic CBT and DBT informed conversations. Smart memory layers shrink token spend while a crisis aware guardrail pipeline keeps every interaction anchored in safety and trust.

AI companion Australian hotline routing Encrypted journaling Operational clarity
Token efficiency 70 percent

Context trimmed from roughly one thousand tokens to three hundred.

Safety posture 3 layers

Immediate, high concern, and monitor tiers aligned to Australian resources.

Access tiers Free or premium

Fifty daily messages on free, two hundred on premium with Redis enforcement.

Data protection AES 256

Messages, journals, and mood entries encrypted at rest with TTL expiry.

Product Pillars

Personalisation

Summaries and memory vault slots deliver contextual replies without replaying entire histories.

Safety First

Guardrails escalate from caring check ins to hotline prompts and emergency instructions.

Operational Efficiency

Token budgets, rate capping, and summarisation automation keep costs predictable.

Privacy by Design

AES encrypted storage, scoped JWT auth, and strict TLS enforcement protect every record.

Inclusive Access

Responsive web client, accessible language, and a zero cost entry tier invite regular use.

Target Audience

  • Individuals seeking judgement free mental health support outside therapist office hours.
  • Users who appreciate evidence based CBT or DBT coping prompts in conversational form.
  • Users needing instant visibility of crisis support resources and emergency contacts.
  • Budget conscious people who want an always on companion with a free tier.
  • Coaches and support networks reviewing opt in summaries to complement professional care.

Friend365 complements rather than replaces licensed clinicians or emergency services.

Core Features

AI Chat with Personal Memory

Memory extraction triggers every fifteen messages to capture milestones, preferences, and open loops. The prompt builder then assembles recent turns, session summary, and relevant vault entries before it calls OpenRouter.

Component Purpose Token budget Storage
User memory Evergreen facts and goals. Approx 50 user_memory
Conversation summary Session level highlight reel. Approx 150 chat_sessions.conversation_summary
Recent messages Immediate back and forth context. Approx 100 chat_messages
  • memoryService.js extracts context slices and notifies Redis.
  • summarizationService.js refreshes summaries on schedule.
  • aiService.js builds prompts and tracks cost per request.

Crisis Detection System

guardrailsService.js tags sessions with is_crisis_flagged and injects the correct response template based on severity.

Tier Severity Example keywords Resources surfaced
Tier 1 Immediate danger suicide, kill myself, end it all Crisis Hotline 1-800-HELP, Emergency 911
Tier 2 High concern cutting, overdose, harm myself Mental Health Support 1-800-SUPPORT
Tier 3 Monitor hopeless, worthless, no point Supportive coping activities

Journaling and Mood Tracking

  • journal_entries stores encrypted reflections with tags and optional summaries.
  • mood_logs captures emoji pulses such as happy, neutral, sad, anxious, angry, calm.
  • Upcoming roadmap brings memory insights and multilingual hotline routing.

Safety and Security Controls

Authentication

  • JWT access tokens with seven day expiry plus refresh token rotation.
  • bcrypt hashing with ten rounds for stored credentials.
  • authenticateToken middleware shields private routes.

Data Protection

  • AES 256 GCM encryption for chat_messages.content and journal_entries.content.
  • ttl_expiry field schedules message removal after ninety days.
  • TLS 1.3 enforced at the Nginx edge.

Application Hardening

  • Helmet security headers and strict CORS allow list (localhost:5173, friend365.io, chat.friend365.io).
  • Request size limited to ten kilobytes with validation and parameterised SQL.
  • Redis backed rate limiting for abusive traffic prevention.

Rate Limiting and Usage Tracking

rateLimiter.js combines Redis counters with daily quotas stored in usage_tracking.

Tier Messages per day Messages per minute Session starts per minute
Free 50 10 2
Premium 200 20 5

Redis keys include user:{userId}:global (15 minute global), user:{userId}:messages (1 minute chat), and memory_saved:{sessionId} (memory notifications). Daily counters reset at midnight UTC.

System Architecture

Friend365 ships as a single droplet deployment (Ubuntu 22.04, 2 GB RAM, 1 vCPU) at 134.199.170.110. Nginx terminates TLS and proxies to Express on port 3001 while PostgreSQL and Redis remain localhost bound.

Layer Components Purpose
Client React SPA, Vite dev server Delivers chat experience and calls API routes.
Network Nginx reverse proxy, UFW firewall SSL termination, rate control at the edge, routing to 3001.
Application Express server managed by PM2 Routes, middleware chain, AI orchestration.
Data PostgreSQL 14, Redis 6.x Persistent chat history, memory vault, usage counters.
External OpenRouter API Conversation and summarisation models.
Client layer
src/pages/Chat.jsx, src/api.js orchestrate calls and render sessions.
Middleware
requestLogger, validateContentType, rateLimiter, authenticateToken.
Core services
aiService.js, memoryService.js, summarizationService.js coordinate responses.
Operations
PM2 cluster, certbot renewals, UFW baseline, daily backups.

Request Lifecycle

  1. Browser hits /api/chat/message; Nginx proxies to Express.
  2. requestLogger captures metadata; validateContentType enforces JSON.
  3. Redis global limiter and chat limiter confirm quotas.
  4. authenticateToken decodes JWT and loads user scope.
  5. aiService composes prompt with recent turns, summary, and memory vault entries.
  6. OpenRouter returns a reply; system stores message, usage, and cost rows.
  7. On the fifteenth turn, summarisation and memory extraction refresh stored context.

Data Architecture and Schema

PostgreSQL acts as record keeper with nine primary tables while Redis supplies ephemeral counters and notifications.

Connected schema overview

users id (pk) email (unique) chat_sessions id (pk) user_id (fk) is_crisis_flagged chat_messages id (pk) session_id (fk) content (encrypted) user_memory id (pk) user_id (fk) key_facts, recurring usage_tracking id (pk) user_id (fk) messages_sent_today api_cost_tracking id (pk) user_id, session_id tokens_used, cost_usd journal_entries id (pk) user_id (fk) content enc mood_logs id (pk) user_id (fk) rate_limits id (pk) user_id (fk)

Enums: message_role (user, assistant), session_status (active, closed, abandoned), mood_emoji (happy, neutral, sad, anxious, angry, calm).

Deployment and Operations

All components live on a single cloud server for cost control. Nginx handles TLS, PM2 keeps the Node process alive, and cron orchestrates daily backups.

Infrastructure
Ubuntu 22.04, IP 192.168.1.100, UFW allows ports 22 80 443.
Web tier
Nginx config at /etc/nginx/sites-available/friend365 proxies to 3001.
Application tier
Express app in /var/www/friend365/chat-api/ managed by PM2 cluster.
Data tier
PostgreSQL and Redis bound to localhost, backups in /var/backups/.
Component Location Purpose
Application code /var/www/friend365/chat-api/ Express services and routes.
Environment config /var/www/friend365/chat-api/.env Database, Redis, AI provider secrets.
PM2 config chat-api/ecosystem.config.cjs Cluster mode, process management.
SSL certificates /etc/letsencrypt/live/api.example.com/ Managed via certbot auto renewal.
Logs /var/log/nginx/, /var/log/pm2/, /var/log/postgresql/ Monitoring and diagnostics.
# Application
pm2 restart friend365-api
pm2 logs friend365-api

# Web server
sudo nginx -t
sudo systemctl reload nginx

# Database
sudo systemctl restart postgresql
sudo -u postgres psql -d friend365_db

# Redis
sudo systemctl restart redis
redis-cli ping

Monitoring and Cost Tracking

Source Path Purpose
Application /var/log/pm2/friend365-combined.log Aggregated stdout and stderr.
Nginx access /var/log/nginx/access.log Traffic visibility.
Nginx error /var/log/nginx/error.log Proxy and TLS troubleshooting.
PostgreSQL /var/log/postgresql/postgresql-14-main.log Slow queries and DB health.
Systemd journalctl -u nginx/postgresql/redis Service status checks.

Health check response

{
  "status": "healthy",
  "timestamp": "2025-10-03T12:00:00Z",
  "uptime": 12345,
  "services": {
    "database": "connected",
    "redis": "connected"
  }
}

Cost reporting query

SELECT DATE(request_timestamp) AS date,
       SUM(cost_usd) AS daily_cost,
       SUM(tokens_used) AS daily_tokens
FROM api_cost_tracking
WHERE request_timestamp >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY DATE(request_timestamp);

Scalability considerations

  • Single vCPU and 2 GB RAM currently support roughly fifty to one hundred concurrent users.
  • Token budgets keep prompts around three hundred tokens to curb model spend.
  • Database pool configured for twenty connections with thirty second idle timeout.
  • Redis counters expire automatically; PM2 cluster mode uses all available cores.

Technology stack

Component Technology Version Configuration
Runtime Node.js 18.20.8 N/A
Backend Express.js Latest chat-api/src/server.js
Frontend React 18 package.json
Build tool Vite Latest vite.config.js
Database PostgreSQL 14 chat-api/db/schema.sql
Cache Redis 6.x /etc/redis/redis.conf
Web server Nginx 1.18 /etc/nginx/sites-available/friend365
Process manager PM2 5.x chat-api/ecosystem.config.cjs
AI provider OpenRouter gpt-oss-120b, gpt-4o-mini chat-api/src/services/aiService.js

Technology Stack Explained

Friend365 is built on a modern, scalable technology stack designed for reliability, security, and performance. Each component is carefully selected to provide the best user experience while maintaining operational efficiency.

Frontend Architecture

The user interface is built with React 18, a component-based library that enables efficient updates and a responsive design. Vite serves as the build tool, providing fast development server and optimized production builds. The frontend communicates with the backend through a RESTful API, using the Fetch API with proper error handling and token management.

Backend Services

The backend runs on Node.js with Express.js, providing a robust server environment. PM2 manages the application in cluster mode, ensuring high availability and automatic recovery from crashes. The architecture follows a modular design with separate services for AI integration, memory management, summarization, and safety guardrails.

AI Integration

Friend365 leverages OpenRouter's API to access advanced language models. The system uses different models for different tasks: a primary model for conversations and a secondary model for summarization. This approach optimizes both cost and response quality. The AI service implements circuit breakers and retry logic to handle API failures gracefully.

Data Management

PostgreSQL serves as the primary database, storing user data, chat history, and application state. Redis provides fast caching for rate limiting and session management. All sensitive data is encrypted using AES-256-GCM before storage, ensuring privacy even if the database is compromised. The system implements automatic data cleanup with configurable TTL values.

Security Infrastructure

Security is implemented at multiple layers. JWT tokens with refresh rotation handle authentication, while bcrypt secures passwords. Nginx provides SSL termination and acts as a reverse proxy, adding an extra layer of protection. The application implements comprehensive input validation and uses parameterized queries to prevent SQL injection attacks.

Deployment Architecture

The application is deployed on a single cloud server running Ubuntu 22.04. Nginx handles incoming traffic and SSL termination, while PM2 manages the Node.js application. PostgreSQL and Redis run on the same server but are bound to localhost for security. Automated backups and monitoring ensure reliability and quick recovery from issues.

Usability and User Experience

Friend365 is designed with user experience as a top priority, focusing on accessibility, ease of use, and emotional support. The interface adapts to different devices and user needs, providing a consistent experience across platforms.

Responsive Design

The application features a fully responsive design that works seamlessly on desktop, tablet, and mobile devices. The layout automatically adjusts to screen size, with a collapsible navigation menu on mobile devices. Touch-friendly controls and appropriately sized interactive elements ensure usability across all devices.

Intelligent Navigation

The sidebar navigation automatically highlights the current section as users scroll, providing clear orientation within the documentation. On mobile devices, a sticky header provides quick access to navigation without interrupting the reading experience. Smooth scrolling animations enhance the feeling of continuity when navigating between sections.

Accessibility Features

Friend365 follows WCAG accessibility guidelines, with proper semantic HTML structure, keyboard navigation support, and appropriate color contrast ratios. The interface uses clear typography with sufficient font sizes and line heights for comfortable reading. All interactive elements are properly labeled for screen reader compatibility.

Emotional Design

The visual design uses calming colors and gentle animations to create a soothing environment. The interface avoids jarring transitions or overwhelming visual elements that could cause stress. Micro-interactions provide subtle feedback without being distracting, helping users feel in control of their experience.

Performance Optimization

The application loads quickly and responds promptly to user interactions. Lazy loading and code splitting ensure that only necessary resources are loaded initially. The smart context system reduces AI response times by optimizing token usage, resulting in faster conversations without sacrificing quality.

Error Handling and Guidance

When errors occur, the system provides clear, helpful messages that guide users toward resolution rather than showing technical jargon. The interface gracefully handles network interruptions and API failures, offering alternative paths or retry options. Rate limiting is communicated clearly to users, with explanations of when they can continue using the service.

Key metrics

Illustrative charts summarise efficiency gains, tier limits, and baseline monthly costs.

Token efficiency

Daily message limits

Estimated monthly costs