From 8bd64d232759865f75f673980bbd48df9fd93ed4 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Wed, 31 Dec 2025 03:39:07 +0000
Subject: [PATCH 1/4] Initial plan
From 94ca2e42dd9b19fecedd03811c4da189bfcc9160 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Wed, 31 Dec 2025 03:49:19 +0000
Subject: [PATCH 2/4] Add project structure, configuration system, and
documentation
Co-authored-by: al7566 <215473224+al7566@users.noreply.github.com>
---
.env.example | 185 ++++++++++++++
.gitignore | 81 +++++++
README.md | 285 +++++++++++++++-------
SETUP_GUIDE.md | 293 ++++++++++++++++++++++
config/keys.js | 174 +++++++++++++
config/validator.js | 253 +++++++++++++++++++
docs/API_SERVICES.md | 523 ++++++++++++++++++++++++++++++++++++++++
package.json | 34 +++
scripts/check-keys.js | 401 ++++++++++++++++++++++++++++++
src/ai/index.js | 61 +++++
src/blueprints/index.js | 82 +++++++
src/calendar/index.js | 83 +++++++
src/index.js | 157 ++++++++++++
src/security/index.js | 78 ++++++
src/voice/index.js | 71 ++++++
15 files changed, 2675 insertions(+), 86 deletions(-)
create mode 100644 .env.example
create mode 100644 .gitignore
create mode 100644 SETUP_GUIDE.md
create mode 100644 config/keys.js
create mode 100644 config/validator.js
create mode 100644 docs/API_SERVICES.md
create mode 100644 package.json
create mode 100644 scripts/check-keys.js
create mode 100644 src/ai/index.js
create mode 100644 src/blueprints/index.js
create mode 100644 src/calendar/index.js
create mode 100644 src/index.js
create mode 100644 src/security/index.js
create mode 100644 src/voice/index.js
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..1cbed75
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,185 @@
+# ====================================
+# AI & Language Processing
+# ====================================
+
+# OpenAI API - Primary AI model (GPT-4)
+# Get it from: https://platform.openai.com/api-keys
+# Required for: AI conversations, text generation, analysis
+OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxxxxxx
+
+# Anthropic Claude API (Optional)
+# Get it from: https://console.anthropic.com/
+# Alternative AI model for enhanced reasoning
+ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxx
+
+# Google Gemini API (Optional)
+# Get it from: https://makersuite.google.com/app/apikey
+# Alternative AI model
+GOOGLE_GEMINI_API_KEY=AIzaXXXXXXXXXXXXXXXXXXXXXXXX
+
+
+# ====================================
+# Voice & Communication
+# ====================================
+
+# Eleven Labs API - Text-to-Speech
+# Get it from: https://elevenlabs.io/
+# Required for: Voice synthesis, natural speech output
+ELEVENLABS_API_KEY=xxxxxxxxxxxxxxxxxxxx
+
+# Deepgram API - Speech-to-Text (Alternative: AssemblyAI)
+# Get it from: https://console.deepgram.com/
+# Required for: Voice recognition, transcription
+DEEPGRAM_API_KEY=xxxxxxxxxxxxxxxxxxxx
+
+# AssemblyAI API - Speech-to-Text (Alternative to Deepgram)
+# Get it from: https://www.assemblyai.com/app/account
+# Optional: Another STT option
+ASSEMBLYAI_API_KEY=xxxxxxxxxxxxxxxxxxxx
+
+# Twilio - Phone Calls & SMS
+# Get it from: https://www.twilio.com/console
+# Required for: Phone calls, SMS messaging
+TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+TWILIO_AUTH_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+TWILIO_PHONE_NUMBER=+1234567890
+
+
+# ====================================
+# Calendar & Scheduling
+# ====================================
+
+# Google Calendar API - OAuth 2.0 Credentials
+# Get it from: https://console.cloud.google.com/apis/credentials
+# Required for: Calendar management, scheduling
+GOOGLE_CALENDAR_CLIENT_ID=xxxxxxxxxxxx.apps.googleusercontent.com
+GOOGLE_CALENDAR_CLIENT_SECRET=GOCSPX-xxxxxxxxxxxxxxxxxxxx
+GOOGLE_CALENDAR_REDIRECT_URI=http://localhost:3000/oauth2callback
+
+# Microsoft Graph API (Optional - for Outlook Calendar)
+# Get it from: https://portal.azure.com/
+# Optional: Outlook calendar integration
+MICROSOFT_CLIENT_ID=xxxxxxxxxxxxxxxxxxxx
+MICROSOFT_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxx
+MICROSOFT_TENANT_ID=xxxxxxxxxxxxxxxxxxxx
+
+
+# ====================================
+# Blueprint/Drawing Tools
+# ====================================
+
+# Google Cloud Vision API - Blueprint Analysis
+# Get it from: https://console.cloud.google.com/
+# Required for: Analyzing CAD drawings, extracting text from blueprints
+GOOGLE_CLOUD_VISION_API_KEY=AIzaXXXXXXXXXXXXXXXXXXXXXXXX
+
+# OpenAI DALL-E 3 (uses same OpenAI key above)
+# Required for: Generating diagrams and visual blueprints
+
+
+# ====================================
+# Cybersecurity
+# ====================================
+
+# VirusTotal API - Malware scanning
+# Get it from: https://www.virustotal.com/gui/my-apikey
+# Required for: File scanning, URL analysis
+VIRUSTOTAL_API_KEY=xxxxxxxxxxxxxxxxxxxx
+
+# Cloudflare API - Security & CDN
+# Get it from: https://dash.cloudflare.com/profile/api-tokens
+# Required for: DNS security, DDoS protection
+CLOUDFLARE_API_KEY=xxxxxxxxxxxxxxxxxxxx
+CLOUDFLARE_ZONE_ID=xxxxxxxxxxxxxxxxxxxx
+
+# Auth0 - Authentication (Alternative: Supabase)
+# Get it from: https://manage.auth0.com/
+# Required for: User authentication
+AUTH0_DOMAIN=your-domain.auth0.com
+AUTH0_CLIENT_ID=xxxxxxxxxxxxxxxxxxxx
+AUTH0_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxx
+
+# Supabase - Authentication & Database (Alternative to Auth0)
+# Get it from: https://app.supabase.com/
+# Optional: Alternative auth provider
+SUPABASE_URL=https://xxxxxxxxxxxx.supabase.co
+SUPABASE_ANON_KEY=xxxxxxxxxxxxxxxxxxxx
+SUPABASE_SERVICE_KEY=xxxxxxxxxxxxxxxxxxxx
+
+# Have I Been Pwned API
+# Get it from: https://haveibeenpwned.com/API/Key
+# Optional: Check for compromised passwords
+HIBP_API_KEY=xxxxxxxxxxxxxxxxxxxx
+
+
+# ====================================
+# Knowledge & Search
+# ====================================
+
+# Perplexity API - AI-powered search
+# Get it from: https://www.perplexity.ai/settings/api
+# Required for: Real-time information retrieval
+PERPLEXITY_API_KEY=pplx-xxxxxxxxxxxxxxxxxxxx
+
+# Bing Search API (Alternative to Perplexity)
+# Get it from: https://portal.azure.com/
+# Optional: Web search capabilities
+BING_SEARCH_API_KEY=xxxxxxxxxxxxxxxxxxxx
+
+# Pinecone - Vector Database
+# Get it from: https://www.pinecone.io/
+# Required for: Knowledge base storage and retrieval
+PINECONE_API_KEY=xxxxxxxxxxxxxxxxxxxx
+PINECONE_ENVIRONMENT=us-east-1-aws
+PINECONE_INDEX_NAME=smart-assistant
+
+# Weaviate - Vector Database (Alternative to Pinecone)
+# Get it from: https://console.weaviate.cloud/
+# Optional: Alternative vector database
+WEAVIATE_URL=https://xxxxxxxxxxxx.weaviate.network
+WEAVIATE_API_KEY=xxxxxxxxxxxxxxxxxxxx
+
+# Wolfram Alpha API - Computational knowledge
+# Get it from: https://products.wolframalpha.com/api/
+# Optional: Advanced calculations and data
+WOLFRAM_ALPHA_APP_ID=XXXXXX-XXXXXXXXXX
+
+
+# ====================================
+# Database & Storage
+# ====================================
+
+# MongoDB Atlas - Database
+# Get it from: https://www.mongodb.com/cloud/atlas
+# Required for: Data persistence
+MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/database
+
+# AWS S3 - File Storage
+# Get it from: https://console.aws.amazon.com/
+# Required for: File uploads, media storage
+AWS_ACCESS_KEY_ID=AKIAXXXXXXXXXXXXXXXX
+AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxx
+AWS_REGION=us-east-1
+AWS_S3_BUCKET=smart-assistant-files
+
+# Cloudinary - Media Storage (Alternative to S3)
+# Get it from: https://cloudinary.com/console
+# Optional: Image/video hosting
+CLOUDINARY_CLOUD_NAME=xxxxxxxxxxxxxxxxxxxx
+CLOUDINARY_API_KEY=xxxxxxxxxxxxxxxxxxxx
+CLOUDINARY_API_SECRET=xxxxxxxxxxxxxxxxxxxx
+
+
+# ====================================
+# Application Configuration
+# ====================================
+
+# Application Settings
+NODE_ENV=development
+PORT=3000
+APP_URL=http://localhost:3000
+
+# Security Settings
+JWT_SECRET=your-random-secret-key-change-this-in-production
+SESSION_SECRET=another-random-secret-key-change-this
+ENCRYPTION_KEY=32-character-encryption-key-here
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4f4080e
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,81 @@
+# Environment variables - NEVER commit these!
+.env
+.env.local
+.env.*.local
+
+# Dependencies
+node_modules/
+package-lock.json
+yarn.lock
+pnpm-lock.yaml
+
+# Logs
+logs/
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+pnpm-debug.log*
+
+# Runtime data
+pids
+*.pid
+*.seed
+*.pid.lock
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+lib-cov
+
+# Coverage directory used by tools like istanbul
+coverage/
+*.lcov
+
+# nyc test coverage
+.nyc_output
+
+# Build output
+dist/
+build/
+.next/
+out/
+
+# Temporary files
+tmp/
+temp/
+*.tmp
+*.temp
+
+# IDE files
+.vscode/
+.idea/
+*.swp
+*.swo
+*~
+.DS_Store
+
+# OS files
+Thumbs.db
+
+# Optional npm cache directory
+.npm
+
+# Optional eslint cache
+.eslintcache
+
+# Optional REPL history
+.node_repl_history
+
+# Diagnostic reports
+report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
+
+# User-specific credential files (encrypted storage)
+credentials/
+keys/
+secrets/
+
+# Google Calendar credentials
+token.json
+credentials.json
+
+# AWS credentials
+.aws/
diff --git a/README.md b/README.md
index 87e3ef4..c8ae4a7 100644
--- a/README.md
+++ b/README.md
@@ -1,86 +1,199 @@
-# SmartAssistant2
-Fix problem.. rewrite code and deploy
-addhcopilot/fix-npm-commands-separationrun: npm install && npm run dev
-
- ...
-VkPhysicalDeviceSamplerYcbcrConversionFeatures::samplerYcbcrConversionSYNC_FDVK_ANDROID_external_memory_android_hardware_buffer# Android 16 features and changes list
-
-
-
-The following table lists all documented features and behavior changes that might affect app developers. Use this list to find changes that affect you, and then click the corresponding link to read the documentation.
-AccessibilityCameraConnectivityCore functionalityGraphicsHealth and fitnessInternationalizationDevice form factorsMediaPerformance and batteryPrivacySecurityUser experience and system UINew features and APIsChange (all apps)Change (apps targeting 16+)
-
-| Category | Type | Name |
-|-------------------------------|-----------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| Core functionality | Change (all apps) | [ART internal changes](https://developer.android.com/about/versions/16/behavior-changes-all#art-changes) Android 16 includes the latest updates to the Android Runtime (ART) that improve the Android Runtime's (ART's) performance and provide support for additional Java features. Through Google Play System updates, these improvements are also available to over a billion devices running Android 12 (API level 31) and higher. As these changes are released, libraries and app code that rely on internal structures of ART might not work correctly on devices running Android 16, along with earlier Android versions that update the ART module through Google Play system updates. |
-| Core functionality | Change (all apps) | [JobScheduler quota optimizations](https://developer.android.com/about/versions/16/behavior-changes-all#job-quota-opt) Android 16 adjusts the regular and expedited job execution runtime quota based on a few factors: which app standby bucket the application is in, whether the job starts execution while the app is in a top state, and whether the job is executing while running a Foreground Service. |
-| Core functionality | Change (all apps) | [Abandoned empty jobs stop reason](https://developer.android.com/about/versions/16/behavior-changes-all#abandoned-job-stop-reason) To detect and reduce abandoned jobs, apps should use the new`STOP_REASON_TIMEOUT_ABANDONED`job stop reason that the system assigns for abandoned jobs, instead of`STOP_REASON_TIMEOUT`. |
-| Core functionality | Change (all apps) | [Ordered broadcast priority scope no longer global](https://developer.android.com/about/versions/16/behavior-changes-all#ordered-broadcast-priority) In Android 16, broadcast delivery order using the[`android:priority`](https://developer.android.com/guide/topics/manifest/intent-filter-element)attribute or[`IntentFilter#setPriority()`](https://developer.android.com/reference/android/content/IntentFilter#setPriority(int))across different processes will not be guaranteed. Broadcast priorities for ordered broadcasts will only be respected within the same application process rather than across all system processes. |
-| Core functionality | Change (all apps) | [16 KB page size compatibility mode](https://developer.android.com/about/versions/16/behavior-changes-all#16-kb-compatibility-mode) Android 15 introduced support for 16 KB memory pages to optimize performance of the platform. Android 16 adds a compatibility mode, allowing some apps built for 4 KB memory pages to run on a device configured for 16 KB memory pages. |
-| Core functionality | Change (apps targeting 16+) | [Fixed rate work scheduling optimization](https://developer.android.com/about/versions/16/behavior-changes-16#schedule-at-fixed-rate) For apps targeting targeting Android 16 or higher, at most one missed execution of[`scheduleAtFixedRate`](https://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService#scheduleAtFixedRate(java.lang.Runnable,%20long,%20long,%20java.util.concurrent.TimeUnit))will be immediately executed when the app returns to a valid lifecycle. |
-| Core functionality | New features and APIs | [Two Android API releases in 2025](https://developer.android.com/about/versions/16/features#two-android) In Android 16, the preview is for the next major release of Android with a planned launch in Q2 of 2025. This release is similar to all of our API releases in the past, where we can have planned behavior changes that are often tied to a targetSdkVersion. We plan to have another release in Q4 of 2025 which also will include new developer APIs. The Q2 major release will be the only release in 2025 to include planned behavior changes that could affect apps. |
-| User experience and system UI | Change (all apps) | [Deprecating disruptive accessibility announcements](https://developer.android.com/about/versions/16/behavior-changes-all#disruptive-a11y) Android 16 deprecates accessibility announcements, characterized by the use of[`announceForAccessibility`](https://developer.android.com/reference/android/view/View#announceForAccessibility(java.lang.CharSequence))or the dispatch of[`TYPE_ANNOUNCEMENT`](https://developer.android.com/reference/android/view/accessibility/AccessibilityEvent#TYPE_ANNOUNCEMENT)accessibility events. |
-| User experience and system UI | Change (all apps) | [Support for 3-button navigation](https://developer.android.com/about/versions/16/behavior-changes-all#three-button-predictive-back) Android 16 brings predictive back support to the 3-button navigation for apps that have properly migrated to predictive back. |
-| User experience and system UI | Change (all apps) | [Automatic themed app icons](https://developer.android.com/about/versions/16/behavior-changes-all#themed-app-icons) Android 16 will automatically apply themes to app icons to create a cohesive home screen experience. |
-| User experience and system UI | Change (apps targeting 16+) | [Elegant font APIs deprecated and disabled](https://developer.android.com/about/versions/16/behavior-changes-16#elegant-text-height) Android 16 deprecates the`elegantTextHeight`attribute, and the attribute will be ignored once your app targets Android 16. |
-| User experience and system UI | Change (apps targeting 16+) | [Edge to edge opt-out going away](https://developer.android.com/about/versions/16/behavior-changes-16#edge-to-edge) For apps targeting Android 16 or higher, the`R.attr#windowOptOutEdgeToEdgeEnforcement`attribute has been removed, requiring apps that were using it to handle window insets. |
-| User experience and system UI | Change (apps targeting 16+) | [Migration or opt-out required for predictive back](https://developer.android.com/about/versions/16/behavior-changes-16#predictive-back) For apps targeting Android 16, system animations such as back-to-home, cross-task, and cross-activity now appear for apps by default. To reflect this in the system, the default value of`android:enableOnBackInvokedCallback`is now`true`, and calls to`OnBackPressed`and`KeyEvent.KEYCODE_BACK`are ignored. |
-| User experience and system UI | New features and APIs | [Predictive back updates](https://developer.android.com/about/versions/16/features#predictive-back-updates) Android 16 adds new APIs to help you enable predictive back system animations in gesture navigation such as the back-to-home animation. Android 16 additionally adds the[`finishAndRemoveTaskCallback()`](https://developer.android.com/reference/android/window/SystemOnBackInvokedCallbacks#finishAndRemoveTaskCallback(android.app.Activity))and[`moveTaskToBackCallback`](https://developer.android.com/reference/android/window/SystemOnBackInvokedCallbacks#moveTaskToBackCallback(android.app.Activity)). |
-| User experience and system UI | New features and APIs | [Richer haptics](https://developer.android.com/about/versions/16/features#rich-haptics) Android 16 adds[haptic APIs](https://developer.android.com/reference/android/os/vibrator/package-summary)that let apps define the amplitude and frequency curves of a haptic effect while abstracting away differences between device capabilities. |
-| User experience and system UI | New features and APIs | [Progress-centric notifications](https://developer.android.com/about/versions/16/features/progress-centric-notifications) Android 16 introduces progress-centric notifications to help users seamlessly track user-initiated, start-to-end journeys. These notifications have upgraded visibility on system surfaces and top ranking in the notification drawer. |
-| User experience and system UI | New features and APIs | [Content handling for live wallpapers](https://developer.android.com/about/versions/16/features#live-wallpapers) In Android 16, the live wallpaper framework is gaining a new content API to address the challenges of dynamic, user-driven wallpapers. |
-| Security | Change (all apps) | [Improved security against Intent redirection attacks](https://developer.android.com/about/versions/16/behavior-changes-all#intent-redirect-attacks) Android 16 introduces by-default security hardening solutions to`Intent`redirection exploits. |
-| Security | Change (all apps) | [Companion apps no longer notified of discovery timeouts](https://developer.android.com/about/versions/16/behavior-changes-all#companion-device-timeout) CDM will no longer notify the app when a device is not found. |
-| Security | Change (apps targeting 16+) | [MediaStore version lockdown](https://developer.android.com/about/versions/16/behavior-changes-16#mediastore-lockdown) For apps targeting Android 16 or higher,`MediaStore#getVersion()`will now be unique to each app. |
-| Security | Change (apps targeting 16+) | [Safer Intents](https://developer.android.com/about/versions/16/behavior-changes-16#safer-intents) For apps targeting Android 16 or higher, the platform provides security improvements to the Android's intent resolution mechanism. |
-| Security | Change (apps targeting 16+) | [GPU syscall filtering](https://developer.android.com/about/versions/16/behavior-changes-16#gpu-syscall-filtering) For apps targeting Android 16 or higher, a high-level SEPolicy is created to allow for fine-grained IOCTL control for the GPU. |
-| Security | New features and APIs | [Key sharing API](https://developer.android.com/about/versions/16/features#key-sharing) Android 16 adds APIs that support sharing access to[Android Keystore](https://developer.android.com/privacy-and-security/keystore)keys with other apps. |
-| Device form factors | Change (all apps) | [Virtual device owner overrides](https://developer.android.com/about/versions/16/behavior-changes-all#virtual-device-owner-overrides) Virtual device owners, limited to select trusted and privileged apps, can now override app settings on devices the virtual device owners manage. |
-| Device form factors | Change (apps targeting 16+) | [Adaptive layouts](https://developer.android.com/about/versions/16/behavior-changes-16#adaptive-layouts) For apps targeting Android 16 or higher, the platform ignores manifest attributes and runtime APIs that restrict screen orientation, aspect ratio, and resizability. |
-| Device form factors | New features and APIs | [Standardized picture and audio quality framework for TVs](https://developer.android.com/about/versions/16/features#media-quality-apis) Android 16 introduces the[`MediaQuality`](https://developer.android.com/reference/android/media/quality/package-summary)package that exposes a set of standardized APIs for access to audio and picture profiles and hardware-related settings. This allows streaming apps to query profiles and apply them to media dynamically. |
-| Connectivity | Change (all apps) | [Improved bond loss handling](https://developer.android.com/about/versions/16/behavior-changes-all#improved-bond-loss-handling) Android 16 improves the handling of bond loss events. |
-| Connectivity | Change (apps targeting 16+) | [New intents to handle bond loss and encryption changes](https://developer.android.com/about/versions/16/behavior-changes-16#new-intents-to-handle-bond-loss) For apps targeting Android 16 or higher, the platform provides two new intents for bond loss and encryption changes. |
-| Connectivity | Change (apps targeting 16+) | [New way to remove bluetooth bond](https://developer.android.com/about/versions/16/behavior-changes-16#bond-removal-api) Apps targeting targeting Android 16 or higher can now use the`removeBond`API to remove bluetooth bonds. |
-| Connectivity | New features and APIs | [Ranging with enhanced security](https://developer.android.com/about/versions/16/features#secure-ranging) Android 16 adds support for[robust security features](https://developer.android.com/reference/android/net/wifi/rtt/SecureRangingConfig)in Wi-Fi location on supported devices with Wi-Fi 6 802.11az, allowing apps to combine the higher accuracy, greater scalability, and dynamic scheduling of the protocol with security enhancements including AES-256-based encryption and protection against MITM attacks. |
-| Connectivity | New features and APIs | [Companion device manager device presence](https://developer.android.com/about/versions/16/features#device-presence) In Android 16, new APIs are being introduced for binding your companion app service. Service will be bound when BLE is in range and Bluetooth is connected and service will be unbound when BLE is out of range or Bluetooth is disconnected. |
-| Connectivity | New features and APIs | [Generic ranging APIs](https://developer.android.com/about/versions/16/features#generic-ranging) Android 16 includes the new[`RangingManager`](https://developer.android.com/reference/android/ranging/RangingManager), which provides ways to determine the distance and angle on supported hardware between the local device and a remote device. |
-| Health and fitness | Change (apps targeting 16+) | [Health and fitness permissions](https://developer.android.com/about/versions/16/behavior-changes-16#health-fitness-permissions) For apps targeting Android 16 or higher, health and fitness permissions are transitioning to a more granular set of permissions under`android.permissions.health`that are used by Health Connect. |
-| Privacy | Change (apps targeting 16+) | [Local Network Permission](https://developer.android.com/about/versions/16/behavior-changes-16#local-network-permission) For apps targeting Android 16 or higher, the platform will require apps to declare a permission to access the local network. |
-| Privacy | Change (apps targeting 16+) | [App-owned photos](https://developer.android.com/about/versions/16/behavior-changes-16#owned-photos) Apps targeting Android 16 and higher now pre-select app-owned photos and videos in the photo picker, allowing users to deselect items to revoke future app access. |
-| Privacy | New features and APIs | [Health Connect updates](https://developer.android.com/about/versions/16/features#health-connect) Health Connect adds`ACTIVITY_INTENSITY`, a new datatype defined according to World Health Organization guidelines around moderate and vigorous activity. Health Connect also contains updated APIs supporting health records. This allows apps to read and write medical records in[FHIR format](https://hl7.org/fhir/)with explicit user consent. This API is in an early access program. If you want to participate,[sign up to be part of our early access program](https://forms.gle/43HJz4Fm2UQLWy5W8). |
-| Privacy | New features and APIs | [Privacy Sandbox on Android](https://developer.android.com/about/versions/16/features#privacy-sandbox) Android 16 incorporates the latest version of the[Privacy Sandbox on Android](https://developers.google.com/privacy-sandbox/overview/android), part of our ongoing work to develop technologies where users know their privacy is protected. |
-| Performance and battery | New features and APIs | [Start component in ApplicationStartInfo](https://developer.android.com/about/versions/16/features#start-component) Android 16 adds[`getStartComponent()`](https://developer.android.com/reference/android/app/ApplicationStartInfo#getStartComponent())to distinguish what component type triggered the start, which can be helpful for optimizing the startup flow of your app. |
-| Performance and battery | New features and APIs | [Adaptive refresh rate](https://developer.android.com/about/versions/16/features#arr) Android 16 introduces[`hasArrSupport()`](https://developer.android.com/reference/android/view/Display#hasArrSupport())and[`getSuggestedFrameRate(int)`](https://developer.android.com/reference/android/view/Display#getSuggestedFrameRate(int))while restoring[`getSupportedRefreshRates()`](https://developer.android.com/reference/android/view/Display#getSupportedRefreshRates())to make it easier for your apps to take advantage of ARR. |
-| Performance and battery | New features and APIs | [Better job introspection](https://developer.android.com/about/versions/16/features#feature-pending-job-reason-history) In Android 16, we're introducing`JobScheduler#getPendingJobReasons()`, which returns multiple reasons why a job is pending, due to both explicit constraints set by the developer and implicit constraints set by the system. We're also introducing`JobScheduler#getPendingJobReasonsHistory()`, which returns the a list of the most recent pending job reason changes. |
-| Performance and battery | New features and APIs | [System-triggered profiling](https://developer.android.com/about/versions/16/features#system-triggered-profiling) Android 16 introduces system-triggered profiling to[`ProfilingManager`](https://developer.android.com/reference/android/app/Activity#reportFullyDrawn()). Apps can register interest in receiving traces for certain triggers such as cold start[`reportFullyDrawn`](https://developer.android.com/reference/android/os/ProfilingManager)or ANRs, and then the system starts and stops a trace on the app's behalf. After the trace completes, the results are delivered to the app's data directory. |
-| Performance and battery | New features and APIs | [Headroom APIs in ADPF](https://developer.android.com/about/versions/16/features#headroom-apis) In Android 16, the[`SystemHealthManager`](https://developer.android.com/sdk/api_diff/b-beta2-incr/changes/android.os.health.SystemHealthManager)introduces the[`getCpuHeadroom`](https://developer.android.com/reference/android/os/health/SystemHealthManager#getCpuHeadroom(android.os.CpuHeadroomParams))and[`getGpuHeadroom`](https://developer.android.com/reference/android/os/health/SystemHealthManager#getGpuHeadroom(android.os.GpuHeadroomParams))APIs, designed to provide games and resource-intensive apps with estimates of available CPU and GPU resources. |
-| Media | New features and APIs | [Photo picker improvements](https://developer.android.com/about/versions/16/features#photo-picker-improvements) Android 16 includes improvements to the photo picker such as new APIs that enable apps to embed the photo picker into their view hierarchy and new APIs that enable searching from the cloud media provider for the Android photo picker. |
-| Media | New features and APIs | [Advanced Professional Video](https://developer.android.com/about/versions/16/features#apv) Android 16 introduces support for the Advanced Professional Video (APV) codec which is designed to be used for professional level high quality video recording and post production. |
-| Camera | New features and APIs | [Precise color temperature and tint adjustments](https://developer.android.com/about/versions/16/features#color-temperature-tint) Android 16 adds camera support for fine color temperature and tint adjustments to better support professional video recording applications. |
-| Camera | New features and APIs | [Hybrid auto-exposure](https://developer.android.com/about/versions/16/features#hybrid-auto-exposure) Android 16 adds new hybrid auto-exposure modes to Camera2, allowing you to manually control specific aspects of exposure while letting the auto-exposure (AE) algorithm handle the rest. |
-| Camera | New features and APIs | [Motion photo capture intent actions](https://developer.android.com/about/versions/16/features#motion-photos) Android 16 adds standard Intent actions ---[`ACTION_MOTION_PHOTO_CAPTURE`](https://developer.android.com/reference/android/provider/MediaStore#ACTION_MOTION_PHOTO_CAPTURE), and[`ACTION_MOTION_PHOTO_CAPTURE_SECURE`](https://developer.android.com/reference/android/provider/MediaStore#ACTION_MOTION_PHOTO_CAPTURE_SECURE)--- which request that the camera application capture a motion photo and return it. |
-| Camera | New features and APIs | [Camera night mode scene detection](https://developer.android.com/about/versions/16/features#night-mode-scene-detection) To help your app know when to switch to and from a night mode camera session, Android 16 adds[`EXTENSION_NIGHT_MODE_INDICATOR`](https://developer.android.com/reference/android/hardware/camera2/CaptureResult#EXTENSION_NIGHT_MODE_INDICATOR). If supported, you can use[`CaptureResult`](https://developer.android.com/reference/android/hardware/camera2/CaptureResult)within Camera2. |
-| Camera | New features and APIs | [UltraHDR image enhancements](https://developer.android.com/about/versions/16/features#ultra-hdr) Android 16 adds support for[UltraHDR images](https://developer.android.com/media/platform/hdr-image-format)in the HEIC file format. |
-| Internationalization | New features and APIs | [Vertical text](https://developer.android.com/about/versions/16/features#vertical-text) Android 16 adds low-level support for rendering and measuring text vertically to provide foundational vertical writing support for library developers. |
-| Internationalization | New features and APIs | [Measurement system customization](https://developer.android.com/about/versions/16/features#measurement-systems) Android 16 adds the ability to customize your measurement system in regional preferences within Settings. |
-| Accessibility | New features and APIs | [Improved accessibility APIs](https://developer.android.com/about/versions/16/features#a11y-apis) Android 16 adds additional APIs to enhance UI semantics that help improve consistency for users that rely on accessibility services, such as[TalkBack](https://developer.android.com/guide/topics/ui/accessibility/testing#talkback). |
-| Accessibility | New features and APIs | [Phone as microphone input for voice calls with LEA hearing aids](https://developer.android.com/about/versions/16/features#lea-phone-input) Android 16 adds the capability for users of LE Audio hearing aids to switch between the built-in microphones on the hearing aids and the microphone on their phone for voice calls. |
-| Accessibility | New features and APIs | [Ambient volume controls for LEA hearing aids](https://developer.android.com/about/versions/16/features#lea-ambient-volume) Android 16 adds the capability for users of LE Audio hearing aids to adjust the volume of ambient sound that is picked up by the hearing aid's microphones. |
-| Graphics | New features and APIs | [Custom graphical effects with AGSL](https://developer.android.com/about/versions/16/features#agsl) Android 16 adds[`RuntimeColorFilter`](https://developer.android.com/reference/android/graphics/RuntimeColorFilter)and[`RuntimeXfermode`](https://developer.android.com/reference/android/graphics/RuntimeXfermode), allowing you to author complex effects like Threshold, Sepia, and Hue Saturation and apply them to draw calls. |val projection = arrayOf(media-database-columns-to-retrieve)
-val selection = sql-where-clause-with-placeholder-variables
-val selectionArgs = values-of-placeholder-variables
-val sortOrder = sql-order-by-clause
-
-applicationContext.contentResolver.query(
- MediaStore.media-type.Media.EXTERNAL_CONTENT_URI,
- projection,
- selection,
- selectionArgs,
- sortOrder
-)?.use { cursor ->
- while (cursor.moveToNext()) {
- // Use an ID column from the projection to get
- // a URI representing the media item itself.
- }
-}const POINTS_PER_LEVEL = 500;
-const newLevel = Math.floor(newTotalPoints / POINTS_PER_LEVEL) + 1;
+# Smart Assistant 2 š¤
+
+A comprehensive AI-powered Smart Assistant with secure key management, voice interaction, calendar integration, cybersecurity monitoring, and blueprint analysis capabilities.
+
+## Features
+
+### š§ Core Smart Assistant Capabilities
+
+- **AI-Powered Conversations** - Natural language processing with GPT-4, Claude, and Gemini
+- **Voice Interaction** - Text-to-speech, speech-to-text, phone calls, and SMS
+- **Calendar & Scheduling** - Google Calendar and Microsoft Outlook integration
+- **Task Management** - Intelligent schedule organization
+- **Cybersecurity Protection** - Real-time threat monitoring and file scanning
+- **Blueprint Creation & Analysis** - CAD drawing capabilities and technical diagram generation
+- **Universal Knowledge Base** - AI-powered search and information retrieval
+
+### š Security & Configuration
+
+- **Secure Key Management** - Environment-based configuration with validation
+- **Setup Wizard** - Interactive key validation with color-coded status
+- **Encrypted Storage** - Safe handling of sensitive credentials
+- **Git-Safe** - Automatic prevention of secret commits
+
+## Quick Start
+
+### 1. Installation
+
+```bash
+# Clone the repository
+git clone https://github.com/al7566/SmartAssistant2.git
+cd SmartAssistant2
+
+# Install dependencies
+npm install
+```
+
+### 2. Configuration
+
+```bash
+# Copy the environment template
+cp .env.example .env
+
+# Edit .env and add your API keys
+nano .env # or use your preferred editor
+```
+
+### 3. Setup Wizard
+
+Run the interactive setup wizard to validate your configuration:
+
+```bash
+npm run check-keys
+```
+
+The wizard will:
+- ā Check which API keys are configured
+- ā Validate key formats
+- ā Test connections to services
+- ā Show which features are available
+
+### 4. Start the Assistant
+
+```bash
+npm start
+```
+
+## Project Structure
+
+```
+SmartAssistant2/
+āāā .env.example # Template for environment variables
+āāā .env # Your actual keys (git-ignored)
+āāā .gitignore # Prevents committing secrets
+āāā package.json # Dependencies and scripts
+āāā README.md # This file
+āāā SETUP_GUIDE.md # Detailed API key setup instructions
+āāā config/
+ā āāā keys.js # Secure key loader
+ā āāā validator.js # Key validation and testing
+āāā scripts/
+ā āāā check-keys.js # Setup wizard/key checker
+āāā src/
+ā āāā index.js # Main application entry
+ā āāā ai/ # AI integration modules
+ā āāā voice/ # Voice interaction
+ā āāā calendar/ # Calendar integration
+ā āāā security/ # Cybersecurity features
+ā āāā blueprints/ # Blueprint handling
+āāā docs/
+ āāā API_SERVICES.md # Detailed API documentation
+```
+
+## Required API Keys
+
+### Essential (Required)
+- ā **OpenAI API** - AI conversations and content generation
+- ā **ElevenLabs** - Text-to-speech
+- ā **Deepgram** - Speech-to-text
+- ā **MongoDB Atlas** - Database storage
+
+### Recommended (Enhanced Features)
+- š” **Twilio** - Phone calls and SMS
+- š” **Google Calendar API** - Calendar management
+- š” **Google Cloud Vision** - Blueprint analysis
+- š” **VirusTotal** - Malware scanning
+- š” **Perplexity AI** - Real-time search
+
+### Optional (Additional Capabilities)
+- āŖ **Anthropic Claude** - Alternative AI model
+- āŖ **Google Gemini** - Multimodal AI
+- āŖ **Pinecone** - Vector database
+- āŖ **Wolfram Alpha** - Computational knowledge
+- āŖ **AWS S3** - File storage
+
+See **[SETUP_GUIDE.md](SETUP_GUIDE.md)** for detailed instructions on obtaining each API key.
+
+## Documentation
+
+- **[SETUP_GUIDE.md](SETUP_GUIDE.md)** - Step-by-step guide for obtaining API keys
+- **[docs/API_SERVICES.md](docs/API_SERVICES.md)** - Detailed API service documentation
+
+## Scripts
+
+```bash
+# Check API key configuration
+npm run check-keys
+
+# Start the Smart Assistant
+npm start
+
+# Development mode (same as start)
+npm run dev
+
+# Run setup wizard
+npm run setup
+```
+
+## Security Best Practices
+
+1. **Never commit `.env`** - It's already in `.gitignore`
+2. **Rotate keys regularly** - Change API keys periodically
+3. **Use environment-specific keys** - Different keys for dev/prod
+4. **Monitor API usage** - Set up billing alerts
+5. **Keep dependencies updated** - Run `npm update` regularly
+
+## Features by Module
+
+### AI Module
+- Natural language conversations
+- Text analysis and summarization
+- Content generation
+- Multiple AI model support (GPT-4, Claude, Gemini)
+
+### Voice Module
+- Text-to-speech with natural voices
+- Speech-to-text transcription
+- Phone call automation
+- SMS messaging
+
+### Calendar Module
+- Event creation and management
+- Schedule optimization
+- Availability checking
+- Multi-calendar support
+
+### Security Module
+- File malware scanning
+- URL threat analysis
+- Password breach checking
+- Real-time threat monitoring
+
+### Blueprint Module
+- Technical drawing analysis
+- OCR for blueprints
+- Diagram generation
+- Blueprint comparison
+
+## Contributing
+
+Contributions are welcome! Please ensure:
+- No API keys are committed
+- Code follows existing patterns
+- Documentation is updated
+- Tests pass (when implemented)
+
+## License
+
+MIT License - See LICENSE file for details
+
+## Support
+
+For issues or questions:
+1. Check the [SETUP_GUIDE.md](SETUP_GUIDE.md)
+2. Review [docs/API_SERVICES.md](docs/API_SERVICES.md)
+3. Open an issue on GitHub
+
+---
+
+**Built with ā¤ļø for intelligent automation**
diff --git a/SETUP_GUIDE.md b/SETUP_GUIDE.md
new file mode 100644
index 0000000..ae87888
--- /dev/null
+++ b/SETUP_GUIDE.md
@@ -0,0 +1,293 @@
+# Smart Assistant 2 - Setup Guide
+
+This guide will walk you through obtaining and configuring all the API keys needed for the Smart Assistant.
+
+## Quick Start
+
+1. **Copy the example environment file:**
+ ```bash
+ cp .env.example .env
+ ```
+
+2. **Install dependencies:**
+ ```bash
+ npm install
+ ```
+
+3. **Run the setup wizard to check your configuration:**
+ ```bash
+ npm run check-keys
+ ```
+
+4. **Add your API keys to `.env` as you obtain them**
+
+5. **Start the assistant:**
+ ```bash
+ npm start
+ ```
+
+## Priority Guide
+
+### š“ Essential (Required for core functionality)
+
+These services are required for the Smart Assistant to run:
+
+#### 1. OpenAI API (GPT-4)
+- **Purpose:** AI conversations, text analysis, content generation
+- **Free Tier:** $5 free credits for new accounts
+- **Paid Tier:** Pay-as-you-go, ~$0.03 per 1K tokens
+
+**How to get it:**
+1. Visit https://platform.openai.com/signup
+2. Create an account
+3. Go to https://platform.openai.com/api-keys
+4. Click "Create new secret key"
+5. Copy the key (starts with `sk-proj-` or `sk-`)
+6. Add to `.env`: `OPENAI_API_KEY=sk-proj-your-key-here`
+
+#### 2. ElevenLabs API (Text-to-Speech)
+- **Purpose:** Convert text to natural-sounding speech
+- **Free Tier:** 10,000 characters/month
+- **Paid Tier:** Starting at $5/month for 30,000 characters
+
+**How to get it:**
+1. Visit https://elevenlabs.io/
+2. Sign up for an account
+3. Go to your profile settings
+4. Copy your API key
+5. Add to `.env`: `ELEVENLABS_API_KEY=your-key-here`
+
+#### 3. Deepgram API (Speech-to-Text)
+- **Purpose:** Convert speech to text for voice commands
+- **Free Tier:** $200 in free credits
+- **Paid Tier:** Pay-as-you-go, $0.0043 per minute
+
+**How to get it:**
+1. Visit https://console.deepgram.com/signup
+2. Create an account
+3. Go to API Keys section
+4. Create a new API key
+5. Add to `.env`: `DEEPGRAM_API_KEY=your-key-here`
+
+#### 4. MongoDB Atlas (Database)
+- **Purpose:** Store user data, conversations, and settings
+- **Free Tier:** 512MB storage (M0 cluster) - Forever free!
+- **Paid Tier:** Starting at $9/month for 2GB
+
+**How to get it:**
+1. Visit https://www.mongodb.com/cloud/atlas/register
+2. Create an account
+3. Create a new cluster (choose the FREE M0 tier)
+4. Click "Connect" ā "Connect your application"
+5. Copy the connection string
+6. Replace `` with your database password
+7. Add to `.env`: `MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/database`
+
+---
+
+### š” Recommended (Enhanced functionality)
+
+These services significantly enhance the assistant's capabilities:
+
+#### 5. Twilio (Phone Calls & SMS)
+- **Purpose:** Make phone calls and send text messages
+- **Free Tier:** $15 trial credit
+- **Paid Tier:** Pay-as-you-go
+
+**How to get it:**
+1. Visit https://www.twilio.com/try-twilio
+2. Sign up and verify your phone number
+3. Go to https://www.twilio.com/console
+4. Copy your Account SID and Auth Token
+5. Buy a phone number (use trial credit)
+6. Add to `.env`:
+ ```
+ TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxx
+ TWILIO_AUTH_TOKEN=your-token-here
+ TWILIO_PHONE_NUMBER=+1234567890
+ ```
+
+#### 6. Google Calendar API
+- **Purpose:** Manage appointments and scheduling
+- **Free Tier:** Completely free!
+
+**How to get it:**
+1. Visit https://console.cloud.google.com/
+2. Create a new project
+3. Enable Google Calendar API
+4. Go to Credentials ā Create Credentials ā OAuth client ID
+5. Configure consent screen
+6. Create OAuth 2.0 Client ID (Web application)
+7. Add authorized redirect URI: `http://localhost:3000/oauth2callback`
+8. Copy Client ID and Client Secret
+9. Add to `.env`:
+ ```
+ GOOGLE_CALENDAR_CLIENT_ID=your-id.apps.googleusercontent.com
+ GOOGLE_CALENDAR_CLIENT_SECRET=GOCSPX-your-secret
+ GOOGLE_CALENDAR_REDIRECT_URI=http://localhost:3000/oauth2callback
+ ```
+
+#### 7. Google Cloud Vision API (Blueprint Analysis)
+- **Purpose:** Analyze blueprints and technical drawings
+- **Free Tier:** 1,000 units/month free
+- **Paid Tier:** $1.50 per 1,000 units
+
+**How to get it:**
+1. Visit https://console.cloud.google.com/
+2. Enable Cloud Vision API
+3. Go to Credentials ā Create Credentials ā API Key
+4. Copy the API key
+5. Add to `.env`: `GOOGLE_CLOUD_VISION_API_KEY=AIzaxxxxxxxx`
+
+#### 8. VirusTotal API (Security Scanning)
+- **Purpose:** Scan files and URLs for malware
+- **Free Tier:** 500 requests/day
+- **Paid Tier:** Starting at $490/month for commercial use
+
+**How to get it:**
+1. Visit https://www.virustotal.com/gui/join-us
+2. Create an account
+3. Go to your profile ā API Key
+4. Copy your API key
+5. Add to `.env`: `VIRUSTOTAL_API_KEY=your-key-here`
+
+#### 9. Perplexity API (AI Search)
+- **Purpose:** Real-time information retrieval with AI
+- **Free Tier:** Limited free queries
+- **Paid Tier:** Pay-as-you-go
+
+**How to get it:**
+1. Visit https://www.perplexity.ai/
+2. Sign up for an account
+3. Go to Settings ā API
+4. Generate an API key
+5. Add to `.env`: `PERPLEXITY_API_KEY=pplx-your-key-here`
+
+---
+
+### āŖ Optional (Additional features)
+
+These services add extra capabilities but aren't required:
+
+#### Anthropic Claude API
+- **Purpose:** Alternative AI model for enhanced reasoning
+- Visit https://console.anthropic.com/
+- Add to `.env`: `ANTHROPIC_API_KEY=sk-ant-xxxxxxxx`
+
+#### Google Gemini API
+- **Purpose:** Another alternative AI model
+- Visit https://makersuite.google.com/app/apikey
+- Add to `.env`: `GOOGLE_GEMINI_API_KEY=AIzaxxxxxxxx`
+
+#### Pinecone (Vector Database)
+- **Purpose:** Advanced knowledge base storage
+- Free Tier: 1 project, 100K vectors
+- Visit https://www.pinecone.io/
+- Add to `.env`: `PINECONE_API_KEY=your-key-here`
+
+#### Wolfram Alpha API
+- **Purpose:** Advanced calculations and data queries
+- Visit https://products.wolframalpha.com/api/
+- Add to `.env`: `WOLFRAM_ALPHA_APP_ID=XXXXXX-XXXXXXXXXX`
+
+#### AWS S3 (File Storage)
+- **Purpose:** Store files and media
+- Free Tier: 5GB storage, 20,000 GET requests/month
+- Visit https://aws.amazon.com/
+- Add to `.env`:
+ ```
+ AWS_ACCESS_KEY_ID=AKIAxxxxxxxx
+ AWS_SECRET_ACCESS_KEY=your-secret-key
+ AWS_REGION=us-east-1
+ AWS_S3_BUCKET=your-bucket-name
+ ```
+
+#### Cloudflare API
+- **Purpose:** Security, CDN, DDoS protection
+- Free Tier: Available
+- Visit https://dash.cloudflare.com/sign-up
+
+#### Auth0 or Supabase
+- **Purpose:** User authentication
+- Both have generous free tiers
+- Auth0: https://auth0.com/signup
+- Supabase: https://app.supabase.com/
+
+---
+
+## Configuration Tips
+
+### Security Best Practices
+
+1. **Never commit your `.env` file** - It's already in `.gitignore`
+2. **Rotate keys regularly** - Change your API keys every few months
+3. **Use environment-specific keys** - Different keys for development/production
+4. **Monitor usage** - Check your API dashboards for unusual activity
+5. **Set up billing alerts** - Get notified if costs exceed expectations
+
+### Cost Management
+
+1. **Start with free tiers** - Most services offer generous free tiers
+2. **Set API rate limits** - Prevent runaway costs
+3. **Monitor usage** - Check dashboards regularly
+4. **Use caching** - Reduce redundant API calls
+5. **Implement quotas** - Limit user requests per day
+
+### Testing Your Setup
+
+After adding keys to your `.env` file, run:
+
+```bash
+npm run check-keys
+```
+
+This will:
+- ā Check which keys are configured
+- ā Validate key formats
+- ā Test connections to services
+- ā Show you what features are available
+
+---
+
+## Troubleshooting
+
+### "API key invalid" errors
+- Double-check you copied the entire key
+- Ensure no extra spaces or quotes
+- Verify the key hasn't expired
+- Check if you need to enable the API in the service dashboard
+
+### Connection timeouts
+- Check your internet connection
+- Verify the service isn't experiencing downtime
+- Some APIs have IP restrictions - check your dashboard
+
+### Free tier limits exceeded
+- Monitor your usage in service dashboards
+- Consider upgrading or using alternative services
+- Implement caching to reduce API calls
+
+---
+
+## Next Steps
+
+Once you've configured your API keys:
+
+1. **Run the setup wizard:** `npm run check-keys`
+2. **Start the assistant:** `npm start`
+3. **Read the API documentation:** `docs/API_SERVICES.md`
+4. **Explore the features** and customize to your needs
+
+---
+
+## Support
+
+If you encounter issues:
+1. Check the service's documentation
+2. Review the error messages in the setup wizard
+3. Ensure all required services are configured
+4. Check that your API keys have the necessary permissions
+
+---
+
+**Happy building! š**
diff --git a/config/keys.js b/config/keys.js
new file mode 100644
index 0000000..5b3e444
--- /dev/null
+++ b/config/keys.js
@@ -0,0 +1,174 @@
+import dotenv from 'dotenv';
+import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
+
+// Load environment variables
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const envPath = join(__dirname, '..', '.env');
+
+dotenv.config({ path: envPath });
+
+/**
+ * Centralized configuration object for all API keys and settings
+ * All sensitive data is loaded from environment variables
+ */
+const config = {
+ // Application Settings
+ app: {
+ env: process.env.NODE_ENV || 'development',
+ port: process.env.PORT || 3000,
+ url: process.env.APP_URL || 'http://localhost:3000',
+ },
+
+ // Security
+ security: {
+ jwtSecret: process.env.JWT_SECRET,
+ sessionSecret: process.env.SESSION_SECRET,
+ encryptionKey: process.env.ENCRYPTION_KEY,
+ },
+
+ // AI & Language Processing
+ ai: {
+ openai: {
+ apiKey: process.env.OPENAI_API_KEY,
+ },
+ anthropic: {
+ apiKey: process.env.ANTHROPIC_API_KEY,
+ },
+ gemini: {
+ apiKey: process.env.GOOGLE_GEMINI_API_KEY,
+ },
+ },
+
+ // Voice & Communication
+ voice: {
+ elevenLabs: {
+ apiKey: process.env.ELEVENLABS_API_KEY,
+ },
+ deepgram: {
+ apiKey: process.env.DEEPGRAM_API_KEY,
+ },
+ assemblyAI: {
+ apiKey: process.env.ASSEMBLYAI_API_KEY,
+ },
+ twilio: {
+ accountSid: process.env.TWILIO_ACCOUNT_SID,
+ authToken: process.env.TWILIO_AUTH_TOKEN,
+ phoneNumber: process.env.TWILIO_PHONE_NUMBER,
+ },
+ },
+
+ // Calendar & Scheduling
+ calendar: {
+ google: {
+ clientId: process.env.GOOGLE_CALENDAR_CLIENT_ID,
+ clientSecret: process.env.GOOGLE_CALENDAR_CLIENT_SECRET,
+ redirectUri: process.env.GOOGLE_CALENDAR_REDIRECT_URI,
+ },
+ microsoft: {
+ clientId: process.env.MICROSOFT_CLIENT_ID,
+ clientSecret: process.env.MICROSOFT_CLIENT_SECRET,
+ tenantId: process.env.MICROSOFT_TENANT_ID,
+ },
+ },
+
+ // Blueprint/Drawing Tools
+ blueprints: {
+ googleVision: {
+ apiKey: process.env.GOOGLE_CLOUD_VISION_API_KEY,
+ },
+ // DALL-E uses the OpenAI key from ai.openai.apiKey
+ },
+
+ // Cybersecurity
+ cybersecurity: {
+ virusTotal: {
+ apiKey: process.env.VIRUSTOTAL_API_KEY,
+ },
+ cloudflare: {
+ apiKey: process.env.CLOUDFLARE_API_KEY,
+ zoneId: process.env.CLOUDFLARE_ZONE_ID,
+ },
+ auth0: {
+ domain: process.env.AUTH0_DOMAIN,
+ clientId: process.env.AUTH0_CLIENT_ID,
+ clientSecret: process.env.AUTH0_CLIENT_SECRET,
+ },
+ supabase: {
+ url: process.env.SUPABASE_URL,
+ anonKey: process.env.SUPABASE_ANON_KEY,
+ serviceKey: process.env.SUPABASE_SERVICE_KEY,
+ },
+ hibp: {
+ apiKey: process.env.HIBP_API_KEY,
+ },
+ },
+
+ // Knowledge & Search
+ knowledge: {
+ perplexity: {
+ apiKey: process.env.PERPLEXITY_API_KEY,
+ },
+ bing: {
+ apiKey: process.env.BING_SEARCH_API_KEY,
+ },
+ pinecone: {
+ apiKey: process.env.PINECONE_API_KEY,
+ environment: process.env.PINECONE_ENVIRONMENT,
+ indexName: process.env.PINECONE_INDEX_NAME,
+ },
+ weaviate: {
+ url: process.env.WEAVIATE_URL,
+ apiKey: process.env.WEAVIATE_API_KEY,
+ },
+ wolframAlpha: {
+ appId: process.env.WOLFRAM_ALPHA_APP_ID,
+ },
+ },
+
+ // Database & Storage
+ database: {
+ mongodb: {
+ uri: process.env.MONGODB_URI,
+ },
+ aws: {
+ accessKeyId: process.env.AWS_ACCESS_KEY_ID,
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
+ region: process.env.AWS_REGION,
+ s3Bucket: process.env.AWS_S3_BUCKET,
+ },
+ cloudinary: {
+ cloudName: process.env.CLOUDINARY_CLOUD_NAME,
+ apiKey: process.env.CLOUDINARY_API_KEY,
+ apiSecret: process.env.CLOUDINARY_API_SECRET,
+ },
+ },
+};
+
+/**
+ * Get a nested configuration value safely
+ * @param {string} path - Dot-notation path (e.g., 'ai.openai.apiKey')
+ * @returns {any} The configuration value or undefined
+ */
+export function getConfig(path) {
+ return path.split('.').reduce((obj, key) => obj?.[key], config);
+}
+
+/**
+ * Check if a specific service is configured
+ * @param {string} path - Dot-notation path to the service config
+ * @returns {boolean} True if the service has at least one configured key
+ */
+export function isServiceConfigured(path) {
+ const serviceConfig = getConfig(path);
+ if (!serviceConfig || typeof serviceConfig !== 'object') {
+ return false;
+ }
+
+ return Object.values(serviceConfig).some(value => {
+ return value !== undefined && value !== null && value !== '';
+ });
+}
+
+export default config;
diff --git a/config/validator.js b/config/validator.js
new file mode 100644
index 0000000..2a22a9b
--- /dev/null
+++ b/config/validator.js
@@ -0,0 +1,253 @@
+/**
+ * API Key Validation Module
+ * Validates format and tests connectivity for various API services
+ */
+
+import axios from 'axios';
+
+/**
+ * Validation rules for different API key formats
+ */
+const keyFormatValidators = {
+ // OpenAI keys start with 'sk-' (legacy) or 'sk-proj-' (new format)
+ openai: (key) => /^sk-(proj-)?[A-Za-z0-9_-]{32,}$/.test(key),
+
+ // Anthropic keys start with 'sk-ant-'
+ anthropic: (key) => /^sk-ant-[A-Za-z0-9_-]{32,}$/.test(key),
+
+ // Google API keys start with 'AIza'
+ google: (key) => /^AIza[A-Za-z0-9_-]{35}$/.test(key),
+
+ // Twilio Account SID starts with 'AC'
+ twilioSid: (key) => /^AC[a-f0-9]{32}$/.test(key),
+
+ // Twilio phone number format
+ twilioPhone: (key) => /^\+?[1-9]\d{1,14}$/.test(key),
+
+ // MongoDB connection string
+ mongodb: (key) => /^mongodb(\+srv)?:\/\/.+/.test(key),
+
+ // AWS Access Key ID format
+ awsAccessKey: (key) => /^AKIA[A-Z0-9]{16}$/.test(key),
+
+ // Perplexity API key starts with 'pplx-'
+ perplexity: (key) => /^pplx-[A-Za-z0-9_-]{32,}$/.test(key),
+
+ // Generic validation for most API keys (at least 20 chars, alphanumeric + common symbols)
+ generic: (key) => key && key.length >= 20 && /^[A-Za-z0-9_\-\.]+$/.test(key),
+
+ // URL validation
+ url: (key) => {
+ try {
+ new URL(key);
+ return true;
+ } catch {
+ return false;
+ }
+ },
+};
+
+/**
+ * Validate API key format
+ * @param {string} key - The API key to validate
+ * @param {string} type - The type of key (openai, google, generic, etc.)
+ * @returns {Object} { valid: boolean, message: string }
+ */
+export function validateKeyFormat(key, type = 'generic') {
+ if (!key || key.trim() === '') {
+ return { valid: false, message: 'Key is empty or missing' };
+ }
+
+ const validator = keyFormatValidators[type] || keyFormatValidators.generic;
+ const isValid = validator(key);
+
+ return {
+ valid: isValid,
+ message: isValid ? 'Format valid' : `Invalid ${type} key format`,
+ };
+}
+
+/**
+ * Test OpenAI API connection
+ */
+export async function testOpenAI(apiKey) {
+ try {
+ const response = await axios.get('https://api.openai.com/v1/models', {
+ headers: { 'Authorization': `Bearer ${apiKey}` },
+ timeout: 5000,
+ });
+ return { success: true, message: 'Connected successfully' };
+ } catch (error) {
+ return {
+ success: false,
+ message: error.response?.status === 401 ? 'Invalid API key' : 'Connection failed',
+ };
+ }
+}
+
+/**
+ * Test Anthropic API connection
+ */
+export async function testAnthropic(apiKey) {
+ try {
+ // Anthropic doesn't have a simple endpoint to test, so we validate format
+ const formatCheck = validateKeyFormat(apiKey, 'anthropic');
+ if (!formatCheck.valid) {
+ return { success: false, message: formatCheck.message };
+ }
+ return { success: true, message: 'Format valid (connection test skipped)' };
+ } catch (error) {
+ return { success: false, message: 'Validation failed' };
+ }
+}
+
+/**
+ * Test ElevenLabs API connection
+ */
+export async function testElevenLabs(apiKey) {
+ try {
+ const response = await axios.get('https://api.elevenlabs.io/v1/voices', {
+ headers: { 'xi-api-key': apiKey },
+ timeout: 5000,
+ });
+ return { success: true, message: 'Connected successfully' };
+ } catch (error) {
+ return {
+ success: false,
+ message: error.response?.status === 401 ? 'Invalid API key' : 'Connection failed',
+ };
+ }
+}
+
+/**
+ * Test Deepgram API connection
+ */
+export async function testDeepgram(apiKey) {
+ try {
+ const response = await axios.get('https://api.deepgram.com/v1/projects', {
+ headers: { 'Authorization': `Token ${apiKey}` },
+ timeout: 5000,
+ });
+ return { success: true, message: 'Connected successfully' };
+ } catch (error) {
+ return {
+ success: false,
+ message: error.response?.status === 401 ? 'Invalid API key' : 'Connection failed',
+ };
+ }
+}
+
+/**
+ * Test Twilio API connection
+ */
+export async function testTwilio(accountSid, authToken) {
+ try {
+ const auth = Buffer.from(`${accountSid}:${authToken}`).toString('base64');
+ const response = await axios.get(`https://api.twilio.com/2010-04-01/Accounts/${accountSid}.json`, {
+ headers: { 'Authorization': `Basic ${auth}` },
+ timeout: 5000,
+ });
+ return { success: true, message: 'Connected successfully' };
+ } catch (error) {
+ return {
+ success: false,
+ message: error.response?.status === 401 ? 'Invalid credentials' : 'Connection failed',
+ };
+ }
+}
+
+/**
+ * Test MongoDB connection
+ */
+export async function testMongoDB(uri) {
+ // MongoDB connection testing requires the mongodb driver
+ // For now, we'll just validate the URI format
+ const formatCheck = validateKeyFormat(uri, 'mongodb');
+ return {
+ success: formatCheck.valid,
+ message: formatCheck.valid ? 'URI format valid' : 'Invalid MongoDB URI format',
+ };
+}
+
+/**
+ * Test VirusTotal API connection
+ */
+export async function testVirusTotal(apiKey) {
+ try {
+ const response = await axios.get('https://www.virustotal.com/api/v3/users/current', {
+ headers: { 'x-apikey': apiKey },
+ timeout: 5000,
+ });
+ return { success: true, message: 'Connected successfully' };
+ } catch (error) {
+ return {
+ success: false,
+ message: error.response?.status === 401 ? 'Invalid API key' : 'Connection failed',
+ };
+ }
+}
+
+/**
+ * Test Perplexity API connection
+ */
+export async function testPerplexity(apiKey) {
+ try {
+ // Perplexity requires a POST request with a body
+ const response = await axios.post(
+ 'https://api.perplexity.ai/chat/completions',
+ {
+ model: 'llama-3.1-sonar-small-128k-online',
+ messages: [{ role: 'user', content: 'test' }],
+ max_tokens: 1,
+ },
+ {
+ headers: {
+ 'Authorization': `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ timeout: 5000,
+ }
+ );
+ return { success: true, message: 'Connected successfully' };
+ } catch (error) {
+ return {
+ success: false,
+ message: error.response?.status === 401 ? 'Invalid API key' : 'Connection failed',
+ };
+ }
+}
+
+/**
+ * Generic API test function
+ * @param {string} name - Service name
+ * @param {string} key - API key
+ * @param {Function} testFn - Custom test function
+ * @returns {Promise