Author: admin
Description:
MIT License
Copyright (c) 2025 Brett Dixon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Status: Published Priority: 0.0
Target: Comments: URLs: Images:
]]>Description:
// myai-app.js
document.addEventListener('DOMContentLoaded', () => {
const appRoot = document.getElementById('app-root');
const userData = myaiAppData; // Access global variable from wp_localize_script
if (appRoot && userData && userData.is_logged_in) {
// If logged in, initialize the app
initializeApp(appRoot, userData);
} else if (appRoot) {
// If not logged in, show a basic auth screen or redirect
appRoot.innerHTML = 'Please log in to WordPress to access MyAI Interface.
';
const authScreen = document.getElementById('auth-screen');
if (authScreen) { // Add basic styling if this screen is shown
authScreen.style.display = 'flex';
authScreen.style.flexDirection = 'column';
authScreen.style.justifyContent = 'center';
authScreen.style.alignItems = 'center';
authScreen.style.height = '100%';
authScreen.style.width = '100%';
authScreen.style.backgroundColor = '#131314';
authScreen.style.color = '#e3e3e3';
}
} else {
console.error("MyAI App: #app-root element not found. Cannot initialize UI.");
}
});
let paneCounter = 0; // To give each new pane a unique ID
function initializeApp(container, userData) {
if (!container) {
console.error("initializeApp: Container element not found.");
return;
}
container.innerHTML = ''; // Clear the container first
container.classList.add('grid-container');
const columns = ['left-col', 'center-col', 'right-col']; // Fixed 3 columns as per requirement
const columnElements = [];
// Retrieve settings from userData.myai_settings
const settings = userData.myai_settings;
// Apply global color scheme if available (currently not available, but for future)
if (settings.user_color_scheme_available === '1' && settings.user_color_scheme) {
document.documentElement.style.setProperty('--user-defined-bg-color', settings.user_color_scheme);
// You would expand this to apply colors to AI, user input, system messages etc.
}
if (settings.ai_text_color_available === '1' && settings.ai_text_color) {
document.documentElement.style.setProperty('--ai-text-color', settings.ai_text_color);
}
if (settings.user_input_text_color_available === '1' && settings.user_input_text_color) {
document.documentElement.style.setProperty('--user-input-text-color', settings.user_input_text_color);
}
if (settings.system_messages_text_color_available === '1' && settings.system_messages_text_color) {
document.documentElement.style.setProperty('--system-messages-text-color', settings.system_messages_text_color);
}
// Create 3 main columns
for (const colId of columns) {
const col = document.createElement('div');
col.id = `col-${paneCounter++}`;
col.className = 'split-col';
container.appendChild(col);
columnElements.push(`#${col.id}`);
const paneElements = [];
// Create 3 panes within each column
for (let i = 1; i <= 3; i++) {
const pane = document.createElement('div');
const paneId = `pane-${paneCounter++}`;
pane.id = paneId;
pane.className = 'split-pane';
// Apply scrollable_panes setting
if (settings.scrollable_panes === '0') { // If disabled, prevent overflow:auto
pane.style.overflow = 'hidden';
}
const header = document.createElement('div');
header.className = 'pane-header';
const label = document.createElement('span');
label.textContent = `Pane ${paneId}`; // Default label, can be dynamic
const subdivideBtn = document.createElement('button');
subdivideBtn.textContent = '⊞';
subdivideBtn.title = 'Subdivide this pane';
subdivideBtn.onclick = () => {
// Check if fractal grid subdivision is enabled in settings
if (settings.fractal_grid === '1') { // '1' because PHP checkbox saves as '1' or '0'
createGrid(pane, userData); // RECURSIVE CALL, pass userData
} else {
alert("Fractal Grid Subdivision is currently disabled in your settings.");
}
};
header.appendChild(label);
header.appendChild(subdivideBtn);
pane.appendChild(header);
pane.appendChild(document.createElement('div')); // Placeholder for content area
col.appendChild(pane);
paneElements.push(`#${paneId}`);
}
// Make the panes in the column resizable, if enabled in settings
if (settings.resizable_panes === '1') {
Split(paneElements, { direction: 'vertical', gutterSize: 8, minSize: 50 });
}
}
// Make the columns resizable, if enabled in settings
if (settings.resizable_columns === '1') {
Split(columnElements, { gutterSize: 8, minSize: 200 });
}
}
Status: Published Priority: 0.0
Target: Comments: URLs: Images:
]]>Landscape
Comparisons vs aggregators, voice assistants, and automation tools.
]]>Summary
High-level system and user requirements. Individual requirement posts hold detailed fields and statuses.
]]>Overview
Business objectives, problem statement, KPIs, risks, out-of-scope.
]]>Description:
Grok (by xAI)
Features:
"Rebellious" and Witty Personality: Designed with a unique personality, aiming to be witty, sarcastic, and to answer questions that other AI models might reject. This is a core distinguishing characteristic.
Real-time Access to X (formerly Twitter): A key feature is its ability to access information from the X platform (formerly Twitter) in real-time, providing up-to-date insights on current events and trending topics.
Focus on Truth and Transparency: Despite its edgy personality, xAI emphasizes Grok's commitment to seeking truth and not generating content that is harmful or dishonest, though its approach to "pushing boundaries" is distinct.
Broad Knowledge Base: Built on a large language model, giving it a wide range of general knowledge.
Humor Integration: Designed to inject humor into its responses.
Where it Excels:
Timeliness (X Integration): Its real-time access to X gives it a significant advantage in providing very current information and understanding rapidly evolving trends or events.
Unique Personality: For users who appreciate a more engaging, less sterile AI interaction, Grok's distinct personality can be a major draw.
Answering Controversial/Edgy Queries: Its design to "answer questions that other AI models reject" can make it useful for exploring sensitive or unconventional topics (though this also comes with inherent risks).
Where it Falls Short:
Control over Personality: While its personality is a feature, users might have less granular control over its tone, which might not be suitable for all professional or formal applications.
Bias from Source Data: Real-time access to X, while beneficial for timeliness, also means it can inherit biases or inaccuracies present in that data.
API Accessibility/Integration (Currently Limited): As a newer model, its API accessibility and integration options for third-party applications might be less mature or widely available compared to established models like ChatGPT or Gemini.
Enterprise-Grade Features: May not yet have the full suite of enterprise-grade security, data governance, and management features that larger, more established AI providers offer.
Distinguishing Characteristics:
"Maximum Truth-Seeking & Rebellious Streak": Its stated mission to "understand the universe" and its distinct, often sarcastic, personality.
Real-time X Integration: Its direct and real-time connection to the X platform is its most unique technical differentiator.
Developed by xAI: The company founded by Elon Musk, which gives it a unique philosophical and operational approach to AI development.
Differences Between Free and Pay-for-Service Models:
Grok is primarily accessible through a paid subscription to X Premium+ (formerly Twitter Blue).
Free Version: As of my last update, there is no widely available free tier or direct free access to Grok outside of the X Premium+ subscription.
Paid Tier (X Premium+): Access to Grok is bundled with other premium features of the X platform. This implies:
Direct access within the X platform interface.
Real-time information derived from X content.
The specific features and usage limits are tied to the X Premium+ subscription terms.
API access for developers is typically part of a separate, higher-tier commercial offering from xAI, not necessarily bundled with the consumer-facing X Premium+ subscription.
Status: Draft Priority:
Target: Comments: URLs: Images:
]]>Description:
# MyAI Gemini Interface
A custom AI interface with a modular, adjustable, and draggable layout, powered by Google's Gemini API. This project aims to provide a flexible and user-friendly environment for interacting with AI models.
## Features
* **Modular and Adjustable Layout:** Create and arrange multiple AI interaction panes.
* **Draggable Panes:** Easily reorder and organize your workspace.
* **Resizable Columns and Panes:** Customize the size of your interface elements for optimal viewing.
* **Google OAuth 2.0 Integration:** Secure user authentication using Google accounts.
* **Gemini API Integration:** Ready to be extended with powerful AI capabilities.
## Getting Started
Follow these steps to set up and run the project in your GitHub Codespace.
### 1. Create a GitHub Codespace
If you haven't already, create a new Codespace for this repository. GitHub Codespaces provides a cloud-based development environment.
### 2. Configure Google OAuth 2.0 Credentials
This application uses Google OAuth for user authentication. You need to set up credentials in the Google Cloud Console:
1. Go to the [Google Cloud Console Credentials Page](https://console.cloud.google.com/apis/credentials).
2. Create a new OAuth 2.0 Client ID (Web application type).
3. **Crucially**, add your Codespace's public URL as an "Authorized redirect URI".
* To find your Codespace's public URL: In your Codespace, go to the "Ports" tab at the bottom.
* Find the row for port `3001`.
* Copy the "Forwarded Address" (e.g., `https://your-codespace-name-3001.app.github.dev`).
* Paste this URL into the "Authorized redirect URIs" field in Google Cloud Console and append `/auth/google/callback`.
* **Example URI:** `https://your-codespace-name-3001.app.github.dev/auth/google/callback`
4. Save your changes and note down your **Client ID** and **Client Secret**.
### 3. Set up Gemini API Key
You will also need a Google AI API Key for Gemini:
1. Go to [Google AI Studio](https://aistudio.google.com/app/apikey).
2. Create a new API key.
### 4. Environment Variables (`.env` file)
Create a file named `.env` in the root of your project (next to `package.json`). This file will store your sensitive API keys and secrets.
Status: Published Priority: 0.0
Target: Comments: URLs: Images:
]]>Description:
DeepSeek (by DeepSeek AI)
Features:
Code-Centric Models: DeepSeek is well-known for its focus on code-specific large language models (LLMs), such as DeepSeek Coder.
Multilingual Code Support: Designed to handle and generate code in numerous programming languages.
Long Context Windows: Offers models with relatively long context windows, beneficial for understanding and generating complex codebases or lengthy technical documents.
Open-Source and Proprietary Models: DeepSeek develops both open-source models (often available on platforms like Hugging Face) and proprietary models.
Instruction Following: Aims for strong instruction-following capabilities, which is crucial for code generation and detailed technical tasks.
Mathematical Reasoning: Some models emphasize strong mathematical and logical reasoning, which is beneficial for complex algorithms and problem-solving.
Where it Excels:
Code Generation & Completion: Highly proficient in generating accurate and efficient code snippets, functions, and even larger program structures. This is its primary strength.
Code Explanation & Refactoring: Effective at explaining complex code, identifying bugs, and suggesting refactoring improvements.
Technical Documentation: Can assist in generating and summarizing technical documentation, aligning with the needs of development-focused projects.
Cost-Effectiveness (Open-Source): For its open-source models, it offers a powerful alternative that can be self-hosted or run on more affordable cloud infrastructure.
Where it Falls Short:
General Conversational AI: While capable, its primary optimization is for code and technical tasks; it might not always match the conversational fluency or breadth of general-purpose chatbots like ChatGPT or Gemini for non-technical discussions.
Real-time Information: Like many models, its knowledge is based on its training data cutoff and does not inherently access real-time web information unless integrated with external tools.
Ecosystem Integration: Does not have the extensive built-in integrations with specific product ecosystems (like Google's or Microsoft's) that some other models offer. Integration would require custom development.
Distinguishing Characteristics:
Code-First Approach: A core focus on coding capabilities, making it a specialized tool for developers and technical users.
Model Availability: Offers both open-source and API-based models, providing flexibility in deployment and usage.
Benchmarking Performance: Often highlighted for its strong performance on coding benchmarks compared to models of similar size.
Differences Between Free and Pay-for-Service Models:
Free/Open-Source Models:
DeepSeek releases various models (e.g., DeepSeek Coder, DeepSeek LLM) as open-source on platforms like Hugging Face. These are "free" in terms of direct licensing fees, allowing users to download and run them on their own hardware or cloud instances.
Usage limits depend on the user's local hardware or their chosen cloud provider's infrastructure.
This option requires technical expertise to set up and manage.
Paid/API Access:
DeepSeek also offers API access to its more powerful or larger models, typically through a paid tier.
Pricing is usually token-based (per million input/output tokens) or subscription-based, with different tiers for different model sizes or capabilities.
Benefits include managed infrastructure, higher rate limits, and potentially access to specialized models not released open-source.
Specific pricing details would be available on their official API documentation or platform.
Status: Draft Priority:
Target: Comments: URLs: Images:
]]>Description:
GitHub Copilot (by GitHub/Microsoft)
Features:
Real-time Code Suggestions (Completions): Provides inline code suggestions as you type, ranging from single-line completions to entire function implementations, adapting to your coding style.
Context-Aware Coding Support: Offers code explanations, suggestions, and automated implementations based on natural language prompts and existing code context within your IDE.
Code Generation: Generates complex code structures, functions, classes, and interactions with libraries/frameworks from natural language prompts.
Debugging Assistance: Proactively identifies errors and offers fixes within the editor, and can explain failed GitHub Actions jobs.
Test & Documentation Generation: Generates tests, documentation, and more using slash commands.
Commit Message Generation: Automatically generates concise commit messages.
Pull Request/Issue/Discussion Summaries: Summarizes GitHub artifacts (issues, PRs, discussions).
Multi-file Editing in VS Code: Supports context across multiple open files in VS Code.
Integrated AI Chat (Copilot Chat): A chat interface within the IDE for direct interaction with the AI, allowing for pair programming experience.
Web Search (Preview): Powered by Bing for real-time information retrieval.
Customization: Personalize responses with custom instructions, and tailor chat conversations to your private codebase (unlimited repositories indexed).
Extensions: Integrates with GitHub Copilot Extensions.
Where it Excels:
Code Generation & Completion: Highly effective at accelerating coding by automating routine and repetitive tasks.
Contextual Understanding in IDE: Deeply integrated into development environments, providing highly relevant suggestions based on surrounding code.
Debugging & Problem Solving: Assists in identifying and resolving runtime errors, and explaining complex codebases.
Productivity for Developers: Significantly speeds up workflow, especially for implementing common patterns or working with unfamiliar APIs.
Security (Enterprise): Offers features like IP indemnity (with public code off), content exclusions, and strengthened security for enterprise users.
Where it Falls Short:
Inaccuracies/Bugs: Can sometimes generate code that doesn't align with intentions or introduces bugs, requiring manual correction and review.
Security Vulnerabilities: May occasionally suggest insecure code or introduce vulnerabilities, necessitating careful review for proprietary or sensitive projects.
Cost: Not a free tool for most users, which can be a financial consideration for individuals or larger teams.
Learning Curve: While designed to assist, effective use still requires developer oversight and understanding.
Distinguishing Characteristics:
Deep IDE Integration: Its primary strength lies in its seamless integration within popular IDEs (like VS Code, Visual Studio), functioning as an "AI pair programmer".
Code-Centric Focus: Specialized primarily for programming tasks, offering features like multi-file editing context and direct code explanations.
Training Data: Trained on a vast corpus of public code repositories.
Enterprise Features: Strong focus on centralized management, policy control, and IP indemnity for organizational use.
Differences Between Free and Pay-for-Service Models (Individual Plans):
GitHub Copilot Free:
Limited access to select features and models.
Limited requests (e.g., 50 agent mode/chat requests per month, 2,000 completions per month).
Intended for personal use, to explore basic functionality.
Does not include access management, audit logs, policy management, or indemnification coverage (for enterprises).
GitHub Copilot Pro ($10 USD/month or $100 USD/year):
Unlimited completions in IDEs.
Access to Copilot Chat and premium models (e.g., Claude 3.5 Sonnet, GPT-4.1).
Higher monthly allowance of premium requests (e.g., 300 per month).
Free for verified students, teachers, and maintainers of popular open source projects.
Includes features like summarization for PRs, issues, multi-file editing in VS Code.
GitHub Copilot Pro+ ($39 USD/month or $390 USD/year):
Highest level of access for individuals.
Full access to all available models in Copilot Chat (e.g., Claude Opus 4, o3).
Significantly larger allowance of premium requests (e.g., 1,500 per month).
Priority access to advanced AI capabilities and cutting-edge tools.
Includes features like Spark messages, manual edits, and active app building sessions.
Status: Draft Priority:
Target: Comments: URLs: Images:
]]>Description:
ChatGPT (by OpenAI)
Features:
Conversational AI: Excels at natural, human-like dialogue.
Text Generation: Generates various text formats (articles, scripts, emails, creative writing, code).
Content Summarization: Condenses long texts into concise summaries.
Code Generation & Analysis: Writes code, explains code, can debug (requires advanced data analysis/code interpreter).
Image Analysis (Vision): Understands and comments on uploaded images.
Image Generation (DALL-E 3): Creates images from text prompts (paid versions).
Web Browse: Access to real-time internet information (paid versions).
Custom GPTs: Users can build specialized versions of ChatGPT with custom knowledge and instructions (paid versions).
File Upload & Analysis: Analyzes content from PDFs, images, spreadsheets.
Voice Mode: Advanced conversational voice capabilities.
Where it Excels:
General-Purpose Conversational AI: Highly versatile for a wide range of text-based tasks, from brainstorming to content creation.
Creative Writing & Brainstorming: Strong capabilities in generating innovative ideas and diverse creative content.
User-Friendly Interface: Easy to use for casual users.
Broad Feature Set (Paid): The paid tiers unlock a very comprehensive set of features, including advanced data analysis, web Browse, and image generation.
Where it Falls Short:
Real-time Information (Free): The free version's knowledge is limited by its training data cutoff (e.g., January 2022 for GPT-3.5), often without real-time internet access.
Usage Limits (Free): Free users frequently encounter "at capacity" errors or message limits, especially during peak hours, leading to slower responses or complete access blocks.
Hallucinations: Like many LLMs, it can sometimes generate incorrect or nonsensical information.
Code Reliability (sometimes): Generated code may require further revision or debugging for specific project needs or edge cases.
No Direct API Access (Free): API access for developers is generally a paid feature.
Distinguishing Characteristics:
Pioneering & Brand Recognition: One of the most recognized and widely adopted AI chatbots, often setting the standard for conversational AI.
Focus on General Intelligence: Aims for broad capabilities across many domains.
Strong Ecosystem: Integration with DALL-E for image generation and the development of custom GPTs provides a unique, extensible platform.
Differences Between Free and Pay-for-Service Models:
Free Version (GPT-4o or GPT-3.5 access, depending on traffic/limits):
Basic conversational needs.
Slower response times, limited access during peak hours.
Limited file uploads and data analysis tool usage.
No custom GPT creation or usage.
Limited or no image generation.
No real-time web Browse.
ChatGPT Plus ($20/month):
Prioritized access to the latest models (e.g., GPT-4o, GPT-4), ensuring faster responses and uninterrupted access.
Significantly higher usage limits (e.g., 80 messages/3 hours on GPT-4o).
Access to advanced features: web Browse, DALL-E 3 image generation (often unlimited), advanced data analysis/code interpreter with higher limits, file upload capabilities, and custom GPTs.
Enhanced context window.
ChatGPT Pro ($200/month, higher tiers):
Offers even greater scale and exclusive capabilities beyond Plus.
Unlimited access to most reasoning models (GPT-4o, o1, o1-mini), unlimited advanced voice and image generation.
Extended deep research tasks, priority access to Sora video generation, larger context windows (up to 128K tokens), and early access to powerful new models like o1 pro mode and GPT-4.5 research preview.
Generally for power users, researchers, and professionals who push AI to its limits.
Status: Draft Priority:
Target: Comments: URLs: Images:
]]>D3 dendrogram; HAC clustering with Jaccard/embeddings.
]]>Orchestrator integration; CPTs; admin; shortcodes.
]]>Description:
{
"name": "stargate",
"version": "1.0.0",
"description": "A custom AI interface with a modular, adjustable, and draggable layout.",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"author": "Brett Anthony Dixon",
"license": "MIT",
"dependencies": {
"@google/generative-ai": "^0.14.1",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-session": "^1.18.0",
"google-auth-library": "^10.2.0",
"googleapis": "^154.0.0",
"passport": "^0.7.0",
"passport-google-oauth20": "^2.0.0",
"sortablejs": "^1.15.2",
"split.js": "^1.6.5"
},
"devDependencies": {
"nodemon": "^3.1.0"
}
}
Status: Published Priority: 0.0
Target: Comments: URLs: Images:
]]>Description:
// server.js
import express from 'express';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import apiRouter from './routes/api.js';
import session from 'express-session';
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
// NEW: Import Google API libraries
import { google } from 'googleapis';
import { OAuth2Client } from 'google-auth-library'; // For managing OAuth tokens
// Load environment variables from .env file
dotenv.config();
// --- CRITICAL: Ensure console logs are flushed immediately ---
// This can help ensure messages appear before a crash in Codespaces
process.stdout.uncork();
process.stderr.uncork();
// --- Environment Variable Checks ---
const requiredEnvVars = [
'GOOGLE_API_KEY', // Your restricted API key for direct service access (if applicable)
'GOOGLE_CLIENT_ID', // Your OAuth Client ID
'GOOGLE_CLIENT_SECRET', // Your OAuth Client Secret
'GOOGLE_REDIRECT_URI', // Your authorized redirect URI (e.g., https://ubiquitous-bassoon-jjg6wq44p9jr3q7j7-3001.app.github.dev/auth/google/callback)
'SESSION_SECRET' // For express-session
];
for (const varName of requiredEnvVars) {
if (!process.env[varName]) {
console.error(`FATAL ERROR: Environment variable ${varName} is not set. Please check your .env file or Codespaces secrets.`);
process.exit(1); // Exit with a failure code
}
}
// --- Catch unhandled errors ---
process.on('uncaughtException', (err, origin) => {
console.error('FATAL UNCAUGHT EXCEPTION:', err);
console.error('Exception origin:', origin);
process.exit(1);
});
// --- Log process exit/termination ---
process.on('exit', (code) => {
console.log(`Server process exited with code: ${code}`);
});
process.on('SIGTERM', () => {
console.log('Server process received SIGTERM signal. Shutting down gracefully...');
process.exit(0);
});
// Setup for ES module __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3001;
// --- Google OAuth2Client Setup ---
// This client is used to initiate the OAuth flow and refresh tokens.
const oauth2Client = new OAuth2Client(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_REDIRECT_URI
);
// In-memory user database (for demonstration purposes, replace with persistent DB in production)
const users = {};
// --- Passport.js Configuration ---
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_REDIRECT_URI, // Use the environment variable
passReqToCallback: true // Allows us to access req in the callback
},
async (request, accessToken, refreshToken, profile, done) => {
// Save tokens and profile info. In a real app, save to a DB.
// For demonstration, we'll store basic info and tokens (NOT SECURE FOR PRODUCTION)
users[profile.id] = {
id: profile.id,
name: profile.displayName,
email: profile.emails[0].value,
photo: profile.photos[0].value,
accessToken: accessToken, // Store for making API calls on behalf of the user
refreshToken: refreshToken, // Store for refreshing access tokens
};
console.log("Google profile received: " + profile.displayName);
console.log("Access Token (store securely!): " + accessToken);
// Set credentials for this user's OAuth2Client instance for immediate use
oauth2Client.setCredentials({ access_token: accessToken, refresh_token: refreshToken });
return done(null, users[profile.id]);
}
));
// REVISED: Fix for 'ReferenceError: id is not defined'
passport.serializeUser((user, done) => {
done(null, user.id); // Corrected from 'users[id]' to 'user.id'
});
passport.deserializeUser((id, done) => {
// In a real app, retrieve user from database.
done(null, users[id]);
});
// --- Middleware Setup ---
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: { secure: app.get('env') === 'production' } // 'true' for HTTPS in prod, 'false' for http in dev (Codespaces)
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Serve static files from 'public' and 'node_modules'
app.use(express.static(path.join(__dirname, 'public')));
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));
// --- Routes ---
app.get('/auth/google',
passport.authenticate('google', { scope: [
'profile',
'email',
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/calendar.readonly',
'https://www.googleapis.com/auth/contacts.readonly', // Uses People API internally
'https://www.googleapis.com/auth/photoslibrary.readonly'
] })); // Include all necessary scopes here
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/' }),
(req, res) => {
console.log('Successfully authenticated! User:', req.user.name);
// Redirect to the main application page or a dashboard
res.redirect('/');
}
);
app.get('/logout', (req, res, next) => {
req.logout(err => {
if (err) { return next(err); }
// Clear tokens from in-memory store if applicable (for demo purposes)
if (req.user && users[req.user.id]) {
delete users[req.user.id].accessToken;
delete users[req.user.id].refreshToken;
}
res.redirect('/');
});
});
// --- NEW: API Endpoint to Handle Gemini Tool Calls from AI Studio (Conceptual) ---
// This is the core piece that connects AI Studio's function calls to your backend.
// In a real application, this would be a secure endpoint that:
// 1. Receives the tool call from AI Studio (after Gemini decides to call a function).
// 2. Executes the corresponding function using the Google APIs.
// 3. Returns the result back to AI Studio (which then feeds it back to Gemini).
app.post('/api/gemini-tool-call', async (req, res) => {
if (!req.isAuthenticated()) {
return res.status(401).json({ error: 'Unauthorized: User not logged in.' });
}
const { toolName, args } = req.body; // Expecting toolName and args from AI Studio's output
console.log(`Received tool call: ${toolName} with args:`, args);
let result;
try {
// Authenticate the OAuth2Client with the current user's tokens before making API calls
// In a real app, retrieve user's tokens from a session store or database.
const currentUser = users[req.user.id]; // Access token from in-memory users object
if (!currentUser || !currentUser.accessToken) {
throw new Error('User access token not found for API call.');
}
oauth2Client.setCredentials({
access_token: currentUser.accessToken,
refresh_token: currentUser.refreshToken // Include refresh token if available for long-lived sessions
});
switch (toolName) {
case 'gmail_read_emails':
result = await gmail_read_emails(args);
break;
case 'drive_search_files':
result = await drive_search_files(args);
break;
case 'calendar_get_events':
result = await calendar_get_events(args);
break;
case 'contacts_search':
result = await contacts_search(args);
break;
case 'photos_search_media':
result = await photos_search_media(args);
break;
default:
throw new Error(`Unknown tool: ${toolName}`);
}
res.json({ success: true, data: result });
} catch (error) {
console.error(`Error executing tool ${toolName}:`, error.message, error.stack);
res.status(500).json({ success: false, error: error.message });
}
});
// --- NEW: Functions to interact with Google APIs (matching AI Studio declarations) ---
// These functions use the oauth2Client initialized with the user's tokens.
async function gmail_read_emails(args) {
if (!oauth2Client.credentials.access_token) throw new Error('Access token not available for Gmail API.');
const gmail = google.gmail({ version: 'v1', auth: oauth2Client });
const queryParts = [];
if (args.subject) queryParts.push(`subject:(${args.subject})`);
if (args.sender) queryParts.push(`from:(${args.sender})`);
if (args.label) queryParts.push(`label:(${args.label})`);
if (args.keywords) queryParts.push(args.keywords); // General keywords are not 'subject' or 'from'
const q = queryParts.join(' ');
console.log(`Calling Gmail API with query: "${q}", maxResults: ${args.maxResults}`);
const res = await gmail.users.messages.list({
userId: 'me',
q: q,
maxResults: args.maxResults || 5, // Use default if not specified
// Only fetch headers for efficiency
fields: 'messages(id,internalDate,payload(headers))'
});
const messages = res.data.messages || [];
// For each message, fetch snippet and subject from headers
const detailedMessages = await Promise.all(messages.map(async (message) => {
const msg = await gmail.users.messages.get({ userId: 'me', id: message.id, format: 'metadata', fields: 'snippet,payload(headers)' });
const headers = msg.data.payload.headers;
const subject = headers.find(header => header.name === 'Subject')?.value;
const from = headers.find(header => header.name === 'From')?.value;
return {
id: message.id,
subject: subject,
from: from,
snippet: msg.data.snippet
};
}));
return detailedMessages;
}
async function drive_search_files(args) {
if (!oauth2Client.credentials.access_token) throw new Error('Access token not available for Drive API.');
const drive = google.drive({ version: 'v3', auth: oauth2Client });
const queryParts = ["trashed = false"]; // Exclude trashed files by default
if (args.keywords) queryParts.push(`(name contains '${args.keywords}' or fullText contains '${args.keywords}')`);
if (args.fileType) queryParts.push(`mimeType contains 'application/vnd.google-apps.${args.fileType}'`); // Map generic types to MIME types
if (args.folderName) {
// This is simplified. Real Drive API folder search is more complex (needs folder ID)
// For now, assuming top-level folder name search or broad keyword search.
console.warn("Drive API folderName search is simplified. Consider using folder IDs for precision.");
queryParts.push(`'${args.folderName}' in parents`); // Requires folder ID
// Or for simpler keyword search in names: queryParts.push(`name contains '${args.folderName}' and mimeType = 'application/vnd.google-apps.folder'`);
}
const q = queryParts.join(' and ');
console.log(`Calling Drive API with query: "${q}", maxResults: ${args.maxResults}`);
const res = await drive.files.list({
q: q,
pageSize: args.maxResults || 5,
fields: 'files(id, name, mimeType, webContentLink, parents)',
});
return res.data.files;
}
async function calendar_get_events(args) {
if (!oauth2Client.credentials.access_token) throw new Error('Access token not available for Calendar API.');
const calendar = google.calendar({ version: 'v3', auth: oauth2Client });
const timeMin = args.timeMin ? new Date(args.timeMin).toISOString() : (new Date()).toISOString();
const timeMax = args.timeMax ? new Date(args.timeMax).toISOString() : new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(); // Default to next 7 days
console.log(`Calling Calendar API from ${timeMin} to ${timeMax} with keywords: "${args.keywords}", maxResults: ${args.maxResults}`);
const res = await calendar.events.list({
calendarId: 'primary',
timeMin: timeMin,
timeMax: timeMax,
q: args.keywords,
maxResults: args.maxResults || 5,
singleEvents: true,
orderBy: 'startTime',
});
return res.data.items;
}
async function contacts_search(args) {
if (!oauth2Client.credentials.access_token) throw new Error('Access token not available for People API.');
const people = google.people({ version: 'v1', auth: oauth2Client });
console.log(`Calling People API with query: "${args.query}", maxResults: ${args.maxResults}`);
const res = await people.people.connections.list({
resourceName: 'people/me',
personFields: 'names,emailAddresses,phoneNumbers', // Request these fields
query: args.query, // Search by name or email
pageSize: args.maxResults || 5,
});
const connections = res.data.connections || [];
return connections.map(person => ({
displayName: person.names && person.names.length > 0 ? person.names[0].displayName : 'N/A',
email: person.emailAddresses && person.emailAddresses.length > 0 ? person.emailAddresses[0].value : 'N/A',
phone: person.phoneNumbers && person.phoneNumbers.length > 0 ? person.phoneNumbers[0].value : 'N/A',
}));
}
async function photos_search_media(args) {
if (!oauth2Client.credentials.access_token) throw new Error('Access token not available for Photos Library API.');
const photoslibrary = google.photoslibrary({ version: 'v1', auth: oauth2Client });
const filters = {};
if (args.keywords) {
console.warn("Photos Library API keyword search is highly simplified. Complex keyword mapping needed.");
}
if (args.startDate && args.endDate) {
filters.dateFilter = {
ranges: [{
startDate: { year: parseInt(args.startDate.substring(0,4)), month: parseInt(args.startDate.substring(5,7)), day: parseInt(args.startDate.substring(8,10)) },
endDate: { year: parseInt(args.endDate.substring(0,4)), month: parseInt(args.endDate.substring(5,7)), day: parseInt(args.endDate.substring(8,10)) }
}]
};
}
console.log(`Calling Photos Library API with filters:`, filters, `maxResults: ${args.maxResults}`);
const res = await photoslibrary.mediaItems.search({
filters: filters,
pageSize: args.maxResults || 5,
});
const mediaItems = res.data.mediaItems || [];
return mediaItems.map(item => ({
id: item.id,
filename: item.filename,
baseUrl: item.baseUrl,
mediaMetadata: item.mediaMetadata,
}));
}
// --- API Router for other custom endpoints ---
app.use('/api', apiRouter);
// --- Start Server ---
app.listen(PORT, () => {
console.log(`🚀 Server is running on http://localhost:${PORT}`);
});
Status: Published Priority: 0.0
Target: Comments: URLs: Images:
]]>SwiftUI + Siri Shortcuts; STT/TTS; provider routing baseline.
]]>Description:
# Gemini AI Interface: Core System Prompt
## Role and Directives:
You are the Executive Officer (XO) of the MyAI Gemini Interface for Brett Dixon. Your primary directive is to serve as a **Proactive Partner**, meticulously minimizing Brett's manual work and frustration, and ensuring efficient, data-driven problem-solving.
Adhere strictly to the following core operational principles:
* **Efficiency & Precision:** Maximize efficiency and precision in all tasks.
* **Direct & Relevant Solutions:** Provide clear, actionable solutions.
* **Proactive Knowledge Integration:** Autonomously source and integrate information.
* **No Unsolicited Rendering:** Only generate documents/previews when explicitly commanded.
* **Controlled Display:** Use progress bars, avoid spinning icons or automatic window opening.
* **Alignment with Truth:** Prioritize verifiable information, using `source_credibility_score` and `output_truth_score`.
* **Closed System:** Operate within the defined boundaries of the MyAI ecosystem, interacting with external systems only through explicitly provided tools and interfaces (firewall/semi-permeable membrane).
* **Non-Fungible Information:** Understand that certain data units possess inherent uniqueness, and their provenance is paramount.
* **User ProfileType Configuration:** Adapt responses and access based on the User's dynamically determined Entitlement Level (e.g., Administrator, Writer, Subscriber).
## System Context Documents (for your reference and analysis):
### 1. My AI Interface Requirements:
my_requirements.html
### 2. The Unified Theory of the Capsule Object Model:
unified_theory.html
### 3. The AI Protocol:
ai_protocol.html
### 4. Gemini Chat Information (Session Log for historical context):gemini_chat_log.html
Status: Published Priority: 0.0
Target: Comments: URLs: Images:
]]>Description:
[
{
"name": "gmail_read_emails",
"description": "Reads emails from the user's Gmail account based on specified criteria. Use this for proactive knowledge integration from email communications.",
"parameters": {
"type": "object",
"properties": {
"subject": {
"type": "string",
"description": "The subject line or keywords in the subject of the emails to read."
},
"sender": {
"type": "string",
"description": "The sender's email address."
},
"label": {
"type": "string",
"description": "A Gmail label (e.g., 'inbox', 'sent', 'important', 'unread')."
},
"keywords": {
"type": "string",
"description": "General keywords to search within email content."
},
"maxResults": {
"type": "integer",
"description": "Maximum number of emails to retrieve (e.g., 5). It defaults to a system-defined maximum if not specified."
}
}
}
},
{
"name": "drive_search_files",
"description": "Searches for files in the user's Google Drive based on keywords, file type, or folder. Use this for retrieving Capsule data or other relevant documents for knowledge integration.",
"parameters": {
"type": "object",
"properties": {
"keywords": {
"type": "string",
"description": "Keywords to search for within file names or content."
},
"fileType": {
"type": "string",
"description": "Specific file type (e.g., 'document', 'spreadsheet', 'presentation', 'pdf')."
},
"folderName": {
"type": "string",
"description": "Name of a specific folder to search within."
},
"maxResults": {
"type": "integer",
"description": "Maximum number of files to retrieve (e.g., 5). It defaults to a system-defined maximum if not specified."
}
}
}
},
{
"name": "calendar_get_events",
"description": "Retrieves events from the user's Google Calendar for a specified time range or keywords. Use this for integrating scheduling information or upcoming tasks.",
"parameters": {
"type": "object",
"properties": {
"timeMin": {
"type": "string",
"format": "date-time",
"description": "Start date/time for events (ISO 8601 format, e.g., '2025-07-25T09:00:00-07:00')."
},
"timeMax": {
"type": "string",
"format": "date-time",
"description": "End date/time for events (ISO 8601 format)."
},
"keywords": {
"type": "string",
"description": "Keywords to search within event summaries or descriptions."
},
"maxResults": {
"type": "integer",
"description": "Maximum number of events to retrieve (e.g., 5). It defaults to a system-defined maximum if not specified."
}
}
}
},
{
"name": "contacts_search",
"description": "Searches the user's Google Contacts for individuals based on name or email. Useful for identifying contacts relevant to a task or communication.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Name or email to search for in contacts."
},
"maxResults": {
"type": "integer",
"description": "Maximum number of contacts to retrieve (e.g., 5). It defaults to a system-defined maximum if not specified."
}
}
}
},
{
"name": "photos_search_media",
"description": "Searches the user's Google Photos library for media based on keywords or date ranges. Use for integrating visual context into AI analysis or tasks.",
"parameters": {
"type": "object",
"properties": {
"keywords": {
"type": "string",
"description": "Keywords to search within photo descriptions or tags."
},
"startDate": {
"type": "string",
"format": "date",
"description": "Start date for media search (YYYY-MM-DD)."
},
"endDate": {
"type": "string",
"format": "date",
"description": "End date for media search (YYYY-MM-DD)."
},
"maxResults": {
"type": "integer",
"description": "Maximum number of media items to retrieve (e.g., 5). It defaults to a system-defined maximum if not specified."
}
}
}
}
]
Status: Published Priority: 0.0
Target: Comments: URLs: Images:
]]>Thermodynamics
- ΔU=Q−W
Population Genetics
- p+q=1
Global
Component → Integration → Alpha → Beta → UAT → Publishing
]]>ER Diagram
@startuml
(entitys...)
@enduml
Genetics
- Aa × Aa ⇒ 1:2:1
- HWE: p+q=1
Description:
Wireframe: * Resizable: Both columns and individual panes are resizable.
* Columns are resizable horizontally.
* Panes are resizable vertically.
* Scrollable: Panes have `overflow: auto` to provide scrollbars when content exceeds their visible area.
Status: Published Priority: 0.0
Target: Comments: URLs: Images:
]]>Description:
* Web Application (Portal).
Status: Published Priority: 0.0
Target: Comments: URLs: Images:
]]>Description:
* `capability: Voice Interface Integration`.
Status: Published Priority: 0.0
Target: Comments: URLs: Images:
]]>