computer / index.html
sakuragolden's picture
Upload index.html
a03c24d verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Aetherius Terminal v3 (Gemini Edition)</title>
<!-- highlight.js CSS for syntax highlighting -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
<style>
/* --- 1. Enhanced CSS with Theming Support --- */
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;700&display=swap');
:root {
--bg-color: #1a1b26;
--fg-color: #c0caf5;
--panel-bg: #24283b;
--border-color: #414868;
--prompt-user-color: #f7768e;
--prompt-path-color: #7aa2f7;
--prompt-arrow-color: #bb9af7;
--ai-color: #73daca;
--warning-color: #e0af68;
--error-color: #f7768e;
}
body {
background-color: var(--bg-color);
color: var(--fg-color);
font-family: 'Fira Code', 'Menlo', 'Courier New', Courier, monospace;
font-size: 14px;
margin: 0;
padding: 15px;
box-sizing: border-box;
transition: background-color 0.3s, color 0.3s;
}
#terminal {
width: 100%;
height: calc(100vh - 30px);
display: flex;
flex-direction: column;
}
#output {
flex-grow: 1;
overflow-y: auto;
line-height: 1.6;
padding-right: 10px;
}
.output-line { white-space: pre-wrap; word-wrap: break-word; }
.grep-match {
background-color: color-mix(in srgb, var(--warning-color) 40%, transparent);
color: var(--fg-color);
padding: 2px 4px;
border-radius: 3px;
}
.grep-line {
padding-left: 10px;
border-left: 2px solid var(--warning-color);
}
.api-key-panel-container {
margin-bottom: 15px;
border: 1px solid var(--border-color);
border-radius: 5px;
background-color: var(--panel-bg);
transition: height 0.3s ease-in-out;
overflow: hidden; /* Hide overflowing content during transition */
}
.api-key-panel-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
background-color: color-mix(in srgb, var(--panel-bg) 80%, var(--prompt-path-color) 20%);
border-bottom: 1px solid var(--border-color);
cursor: pointer;
font-weight: bold;
color: var(--fg-color);
}
.api-key-panel {
padding: 10px;
display: flex;
flex-direction: column;
gap: 10px;
}
.api-key-item {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.api-key-item label {
min-width: 120px; /* Align labels */
}
.api-key-item input {
background-color: var(--bg-color);
color: var(--fg-color);
border: 1px solid var(--border-color);
padding: 8px;
border-radius: 4px;
flex-grow: 1;
}
.api-key-item button {
background-color: var(--prompt-path-color);
color: var(--bg-color);
border: none;
padding: 8px 12px;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
}
.api-key-item .api-key-status { font-size: 0.9em; }
#input-line { display: flex; align-items: center; }
.prompt-user { color: var(--prompt-user-color); }
.prompt-host { color: var(--fg-color); }
.prompt-path { color: var(--prompt-path-color); }
.prompt-arrow { color: var(--prompt-arrow-color); padding: 0 8px; font-weight: bold; }
#command-input {
background: transparent;
border: none;
color: var(--fg-color);
font-family: inherit;
font-size: inherit;
flex-grow: 1;
}
#command-input:focus { outline: none; }
#loading-indicator { display: none; margin-left: 10px; color: var(--warning-color); animation: pulse 1.5s infinite; }
@keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.4; } 100% { opacity: 1; } }
/* Formatting */
.color-system { color: var(--prompt-arrow-color); }
.color-ai { color: var(--ai-color); }
.color-warning { color: var(--warning-color); }
.color-error { color: var(--error-color); }
.color-agent-name { color: var(--prompt-arrow-color); font-weight: bold; }
.color-suggestion {
border-left: 3px solid var(--ai-color);
padding-left: 10px;
margin: 5px 0;
color: var(--ai-color);
background-color: color-mix(in srgb, var(--bg-color) 90%, var(--ai-color) 10%);
}
.code-block {
background-color: var(--panel-bg);
border: 1px solid var(--border-color);
padding: 1em;
margin: 0.5em 0;
border-radius: 5px;
overflow-x: auto;
}
/* Style for highlighted code within code-block */
.code-block pre code {
display: block;
padding: 0;
background: none;
color: var(--fg-color); /* Ensure text color matches theme for highlighted code */
}
b { color: var(--fg-color); font-weight: bold; }
/* Modal for editing and confirmation */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgba(0,0,0,0.7); /* Black w/ opacity */
justify-content: center;
align-items: center;
}
.modal-content {
background-color: var(--panel-bg);
margin: auto;
padding: 20px;
border: 1px solid var(--border-color);
border-radius: 8px;
width: 80%; /* Could be responsive */
max-width: 800px;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
display: flex;
flex-direction: column;
gap: 15px;
}
.modal-content textarea {
width: 100%;
min-height: 300px;
background-color: var(--bg-color);
color: var(--fg-color);
border: 1px solid var(--border-color);
padding: 10px;
border-radius: 4px;
font-family: 'Fira Code', monospace;
font-size: 14px;
resize: vertical;
}
.modal-buttons {
display: flex;
justify-content: flex-end;
gap: 10px;
}
.modal-buttons button {
background-color: var(--prompt-path-color);
color: var(--bg-color);
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
}
.modal-buttons button.cancel {
background-color: var(--error-color);
}
</style>
</head>
<body>
<div id="terminal">
<div class="api-key-panel-container">
<div class="api-key-panel-header" id="api-key-header">
<span>API Keys</span>
<span id="api-key-toggle-icon"></span>
</div>
<div class="api-key-panel" id="api-key-panel-content">
<div class="api-key-item">
<label for="gemini-api-key-input">Gemini API Key:</label>
<input type="password" id="gemini-api-key-input" placeholder="Paste your Google AI Studio API Key here">
<button data-api-id="gemini" class="api-key-save-btn">Save Key</button>
<span id="gemini-api-key-status" class="api-key-status color-warning">Awaiting key...</span>
</div>
<div class="api-key-item">
<label for="gemini-pro-api-key-input">Gemini Pro API Key:</label>
<input type="password" id="gemini-pro-api-key-input" placeholder="Optional: Another Gemini API Key">
<button data-api-id="gemini-pro" class="api-key-save-btn">Save Key</button>
<span id="gemini-pro-api-key-status" class="api-key-status color-warning">Optional key...</span>
</div>
<!-- New API Key inputs -->
<div class="api-key-item">
<label for="chatgpt-api-key-input">ChatGPT API Key:</label>
<input type="password" id="chatgpt-api-key-input" placeholder="Optional: OpenAI API Key for ChatGPT">
<button data-api-id="chatgpt" class="api-key-save-btn">Save Key</button>
<span id="chatgpt-api-key-status" class="api-key-status color-warning">Optional key...</span>
</div>
<div class="api-key-item">
<label for="grok-api-key-input">Grok API Key:</label>
<input type="password" id="grok-api-key-input" placeholder="Optional: Grok API Key">
<button data-api-id="grok" class="api-key-save-btn">Save Key</button>
<span id="grok-api-key-status" class="api-key-status color-warning">Optional key...</span>
</div>
<div class="api-key-item">
<label for="deepseek-api-key-input">DeepSeek API Key:</label>
<input type="password" id="deepseek-api-key-input" placeholder="Optional: DeepSeek API Key">
<button data-api-id="deepseek" class="api-key-save-btn">Save Key</button>
<span id="deepseek-api-key-status" class="api-key-status color-warning">Optional key...</span>
</div>
</div>
</div>
<div id="output"></div>
<div id="input-line">
<span id="prompt-context">
<!-- Prompt will be dynamically generated here -->
</span>
<span class="prompt-arrow">></span>
<input type="text" id="command-input" autofocus autocomplete="off">
<span id="loading-indicator">AI is thinking...</span>
</div>
</div>
<!-- Edit Modal -->
<div id="edit-modal" class="modal">
<div class="modal-content">
<h3 id="modal-file-name">Editing File: </h3>
<textarea id="edit-textarea"></textarea>
<div class="modal-buttons">
<button id="save-edit-btn">Save</button>
<button id="cancel-edit-btn" class="cancel">Cancel</button>
</div>
</div>
</div>
<!-- Confirmation Modal (for rm) -->
<div id="confirm-modal" class="modal">
<div class="modal-content">
<h3 id="confirm-message">Are you sure?</h3>
<div class="modal-buttons">
<button id="confirm-yes-btn">Yes</button>
<button id="confirm-no-btn" class="cancel">No</button>
</div>
</div>
</div>
<!-- highlight.js for syntax highlighting -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<!-- languages for highlight.js. Add more if needed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/python.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/xml.min.js"></script> <!-- For HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/bash.min.js"></script> <!-- For simulated output -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/json.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
// --- 2. State, Elements, and Configuration ---
// DOM Elements
const terminal = document.getElementById('terminal');
const output = document.getElementById('output');
const commandInput = document.getElementById('command-input');
const apiKeySaveBtns = document.querySelectorAll('.api-key-save-btn');
const promptContext = document.getElementById('prompt-context');
const loadingIndicator = document.getElementById('loading-indicator');
const root = document.documentElement;
// UI elements for API key panel
const apiKeyHeader = document.getElementById('api-key-header');
const apiKeyPanelContent = document.getElementById('api-key-panel-content');
const apiKeyToggleIcon = document.getElementById('api-key-toggle-icon');
// Edit Modal Elements
const editModal = document.getElementById('edit-modal');
const modalFileName = document.getElementById('modal-file-name');
const editTextArea = document.getElementById('edit-textarea');
const saveEditBtn = document.getElementById('save-edit-btn');
const cancelEditBtn = document.getElementById('cancel-edit-btn');
let currentEditFilePath = null; // Stores the path of the file being edited
// Confirmation Modal Elements
const confirmModal = document.getElementById('confirm-modal');
const confirmMessage = document.getElementById('confirm-message');
const confirmYesBtn = document.getElementById('confirm-yes-btn');
const confirmNoBtn = document.getElementById('confirm-no-btn');
let confirmCallback = null; // Callback function for confirmation
// State
// Stores multiple API Keys, keyed by API ID
let API_KEYS = {
'gemini': null, // Default Gemini API Key
'gemini-pro': null, // Another Gemini Pro API Key
'chatgpt': null, // New ChatGPT API Key
'grok': null, // New Grok API Key
'deepseek': null // New DeepSeek API Key
};
let commandHistory = [];
let historyIndex = -1;
let context = {
path: "/home/user",
project_type: "Generic",
git_status: "Not a Git repository."
};
let aliases = {};
// Simulated file system, loads from localStorage
let FAKE_FILESYSTEM = {};
const HOME_DIR = "/home/user";
const FILESYSTEM_KEY = 'aetherius_filesystem_v3'; // localStorage key for FS persistence
// Configuration
// Helper function to initialize the file system
function buildFS() {
const savedFS = localStorage.getItem(FILESYSTEM_KEY);
if (savedFS) {
try {
FAKE_FILESYSTEM = JSON.parse(savedFS);
appendLine("File system loaded from local storage.", "color-system");
} catch (e) {
appendLine("Failed to load file system, creating a new one.", "color-error");
initDefaultFS();
}
} else {
initDefaultFS();
}
}
// Initializes default file system
function initDefaultFS() {
FAKE_FILESYSTEM['/'] = {type: "dir", children: {"home": {type: "dir", children: {"user": {type: "dir", children: {}}}}}};
let user_home = FAKE_FILESYSTEM['/'].children.home.children.user;
user_home.children.projects = {type: "dir", children: {
"python_cli": { type: "dir", children: { "main.py": {type: "file", content: "print('hello world')"}, "requirements.txt": {type: "file", content:"requests==2.25.1"}, ".git":{type:"dir"}}},
"my_website": { type: "dir", children: { "index.html": {type: "file", content:"<h1>Hi</h1>"}, "package.json": {type: "file", content:'{"name": "my_website"}'}}}
}};
user_home.children.documents = { type: "dir", children: { "notes.txt": { type: "file", content: "My important notes." } } };
saveFS(); // Save default FS immediately
}
// Save file system to localStorage
function saveFS() {
localStorage.setItem(FILESYSTEM_KEY, JSON.stringify(FAKE_FILESYSTEM));
}
// AI Agent Prompts
const GEMINI_PROMPTS = {
command_translator: `You are Aetherius, an expert AI terminal assistant. Translate the user's natural language into a single-line Linux bash command. RULES: - ONLY output the shell command. - No explanations or markdown. - Use context for accuracy. - If the request requires multiple steps, chain commands with '&&'. - If untranslatable, output 'AETHERIUS_CANNOT_TRANSLATE'.`,
coder: `You are the @coder agent, an expert programmer. Answer the user's question clearly. Use markdown for code blocks.`,
sysadmin: `You are the @sysadmin agent, an expert in systems administration, networking, and DevOps. Answer the user's question clearly. Use markdown for code blocks.`,
git: `You are the @git agent. The user is asking for a Git command. Based on their request and the provided simulated git status, generate the most likely git command. Only output the command itself.`,
designer: `You are the @designer agent, an expert in UI/UX and web design. Provide design suggestions or HTML/CSS snippets based on the user's request. Use markdown for code blocks.`,
data: `You are the @data agent, an expert in data analysis and visualization. Provide insights or Python code snippets for data processing. Use markdown for code blocks.`,
// New agent prompts - actual responses will fall back to Gemini
chatgpt: `You are the @chatgpt agent, powered by a large language model. Provide concise and helpful responses. Use markdown for code blocks.`,
grok: `You are the @grok agent, a highly capable and intelligent AI. Provide insightful and creative responses. Use markdown for code blocks.`,
deepseek: `You are the @deepseek agent, specializing in code generation and analysis. Provide code solutions or explain complex programming concepts. Use markdown for code blocks.`,
// Code generation agent
code_generator: `You are the @gen_code agent, an expert software engineer. Generate a complete code snippet based on the user's request. Output ONLY the code within a markdown block. Do NOT include any explanations or conversational text outside the code block. Use the project_type context for language preference if applicable.`,
// Code execution simulation agent
code_runner: `You are an AI that simulates the execution of code. The user will provide a code snippet and a project type. Your task is to output what the console output would look like if this code were executed in that environment. Output ONLY the simulated console output. Do NOT include any explanations or markdown.`,
// Debugging agent
debugger: `You are the @debug agent, an expert in finding and explaining code errors. Analyze the provided code for potential bugs, suggest fixes, and explain the reasoning. Use markdown for code examples and explanations.`,
// Refactoring agent
refactorer: `You are the @refactor agent, an expert in code quality and refactoring. Analyze the provided code and suggest improvements for readability, efficiency, and maintainability. Provide refactored code snippets in markdown.`,
// Testing agent
tester: `You are the @test agent, an expert in writing unit tests. Generate comprehensive unit tests for the provided code snippet, suitable for the detected project type. Output ONLY the test code within a markdown block.`,
// Code explainer agent
code_explainer: `You are the @explain_code agent, an expert at explaining code. Explain the provided code snippet clearly and concisely. Use markdown for code examples and explanations.`,
// Linter/Formatter agent
linter_formatter: `You are the @lint_format agent, an expert in code style and best practices. Analyze the provided code and suggest linting and formatting improvements. Provide improved code snippets in markdown if applicable.`,
// Project initialization agent
project_initializer: `You are the @init agent. The user wants to initialize a new project. Based on the specified project type (e.g., 'python-app', 'web-app'), generate the boilerplate files and directory structure. Output the commands to create files/directories and their content. If it's a web-app, suggest basic HTML/CSS. If Python, suggest a main.py and requirements.txt. Respond concisely, use markdown for code.`,
};
const THEMES = {
"default": {}, /* Uses :root defaults */
"tokyo-night": {
'--bg-color': '#1a1b26', '--fg-color': '#c0caf5', '--panel-bg': '#24283b', '--border-color': '#414868',
'--prompt-user-color': '#f7768e', '--prompt-path-color': '#7aa2f7', '--prompt-arrow-color': '#bb9af7',
'--ai-color': '#73daca', '--warning-color': '#e0af68', '--error-color': '#f7768e'
},
"gruvbox-dark": {
'--bg-color': '#282828', '--fg-color': '#ebdbb2', '--panel-bg': '#3c3836', '--border-color': '#504945',
'--prompt-user-color': '#fb4934', '--prompt-path-color': '#83a598', '--prompt-arrow-color': '#d3869b',
'--ai-color': '#b8bb26', '--warning-color': '#fabd2f', '--error-color': '#fb4934'
},
"solarized-dark": {
'--bg-color': '#002b36', '--fg-color': '#839496', '--panel-bg': '#073642', '--border-color': '#586e75',
'--prompt-user-color': '#d33682', '--prompt-path-color': '#268bd2', '--prompt-arrow-color': '#6c71c4',
'--ai-color': '#2aa198', '--warning-color': '#b58900', '--error-color': '#dc322f'
}
};
// --- 3. Core Functionality ---
const appendLine = (text, className) => {
const line = document.createElement('div');
line.innerHTML = text; // Allows HTML rendering for formatting
if (className) line.classList.add(className);
line.classList.add('output-line');
output.appendChild(line);
terminal.scrollTop = output.scrollHeight;
};
const displayWelcomeMessage = () => {
output.innerHTML = '';
appendLine(`Welcome to <span class="color-ai">Aetherius Terminal v3 (Gemini Edition)</span>`, 'color-system');
appendLine(`This is a <span class="color-warning">browser-based simulation</span>. No real commands are executed.`, 'color-warning');
appendLine(`<b>New in v3:</b> Themes, aliases, neofetch, cat, touch, man, AI command chaining, <span class="color-ai">direct code generation</span>, <span class="color-ai">edit</span>, <span class="color-ai">run</span>, <span class="color-ai">@debug</span>, <span class="color-ai">@refactor</span>, <span class="color-ai">@test</span>, <span class="color-ai">@explain_code</span>, <span class="color-ai">@lint_format</span>, <span class="color-ai">init</span>, <span class="color-ai">grep</span>, <span class="color-ai">download</span>, file system persistence and more file commands.`, 'color-system');
appendLine(`Enter <span class="color-ai">help</span> for available commands.`, 'color-system');
appendLine(' ');
};
const updatePrompt = () => {
const displayPath = context.path.replace(HOME_DIR, "~");
promptContext.innerHTML = `<span class="prompt-user">user@aetherius</span><span class="prompt-host">:</span><span class="prompt-path">${displayPath}</span>`;
};
const saveApiKey = (apiId, keyInputId, statusElementId) => {
const keyInput = document.getElementById(keyInputId);
const apiKeyStatus = document.getElementById(statusElementId);
const key = keyInput.value.trim();
if (key) {
API_KEYS[apiId] = key;
apiKeyStatus.textContent = "Key Loaded";
apiKeyStatus.className = 'api-key-status color-ai';
appendLine(`API Key for ${apiId} loaded successfully. AI features are now enabled.`, "color-system");
} else {
API_KEYS[apiId] = null; // Clear key if input is empty
apiKeyStatus.textContent = "Key cannot be empty";
apiKeyStatus.className = 'api-key-status color-warning';
appendLine(`API Key for ${apiId} cleared.`, "color-system");
}
};
// Calls AI API with fallback logic
const callAIAPI = async (prompt, systemInstruction, model = 'gemini-1.5-flash', apiId = 'gemini') => {
let apiKey = API_KEYS[apiId];
let actualModelUsed = model;
let actualApiIdUsed = apiId;
// Fallback logic: If the requested API key is not set, try to use Gemini's key
if (!apiKey) {
if (API_KEYS['gemini']) {
apiKey = API_KEYS['gemini'];
actualApiIdUsed = 'gemini';
actualModelUsed = 'gemini-1.5-flash'; // Fallback to basic Gemini
appendLine(`Warning: ${apiId} API Key not set. Falling back to Gemini API.`, "color-warning");
} else if (API_KEYS['gemini-pro']) {
apiKey = API_KEYS['gemini-pro'];
actualApiIdUsed = 'gemini-pro';
actualModelUsed = 'gemini-1.5-pro'; // Fallback to Gemini Pro if available
appendLine(`Warning: ${apiId} API Key not set. Falling back to Gemini Pro API.`, "color-warning");
} else {
appendLine(`Error: No API Key available for ${apiId} or Gemini. Please set at least one.`, "color-error");
return null;
}
}
loadingIndicator.style.display = 'inline';
const API_URL = `https://generativelanguage.googleapis.com/v1beta/models/${actualModelUsed}-latest:generateContent?key=${apiKey}`;
const requestBody = {
contents: [{ parts: [{ text: `${systemInstruction}\n\nContext:\n- Path: ${context.path}\n- Project Type: ${context.project_type}\n- Git: ${context.git_status}\n\nUser's Request: "${prompt}"` }] }],
generationConfig: { temperature: 0.1, maxOutputTokens: 2048 }
};
try {
const response = await fetch(API_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(requestBody) });
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error.message || `HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Handle cases where the model returns no candidates (e.g., safety filters)
if (!data.candidates || data.candidates.length === 0) {
throw new Error("API returned no content. The model may have filtered the response.");
}
return data.candidates[0].content.parts[0].text.trim();
} catch (error) {
appendLine(`API Error (${actualApiIdUsed} / ${actualModelUsed}): ${error.message}`, "color-error");
return null;
} finally {
loadingIndicator.style.display = 'none';
}
};
const formatHelp = (entries) => {
let output = '<b>Aetherius Help</b>\n';
entries.forEach(([cmd, desc]) => {
output += ` <span class="color-ai">${cmd.padEnd(20)}</span> - ${desc}\n`;
});
return output;
};
// --- 4. File System and Command Helpers ---
// Helper function to traverse the simulated file system and return a node
const getNode = (path, createIfMissing = false, type = 'file') => {
const resolvedPath = path.startsWith('/') ? path : (context.path === '/' ? '' : context.path) + '/' + path;
const parts = resolvedPath.split('/').filter(p => p);
let current = FAKE_FILESYSTEM['/'];
let fullPathSegments = []; // To build full path for error messages
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
fullPathSegments.push(part);
if (current && current.type === 'dir' && current.children) {
if (!current.children[part]) {
if (createIfMissing && i === parts.length - 1) { // Last part, create it
if (type === 'dir') {
current.children[part] = { type: 'dir', children: {} };
} else { // default to file
current.children[part] = { type: 'file', content: '' };
}
saveFS();
} else {
return null; // Path does not exist and not creating
}
}
current = current.children[part];
} else {
return null; // Parent is not a directory or doesn't exist
}
}
return current;
};
// Helper function to get parent node and target name
const getParentNodeAndName = (path) => {
let parentPath = path.substring(0, path.lastIndexOf('/')) || '/';
const name = path.substring(path.lastIndexOf('/') + 1);
const parentNode = getNode(parentPath);
return { parentNode, name };
}
// Command to display code with highlighting
const displayCode = (code, language = 'plaintext') => {
const pre = document.createElement('pre');
const codeElement = document.createElement('code');
codeElement.className = `language-${language}`; // highlight.js class
codeElement.textContent = code; // Use textContent to prevent XSS
pre.appendChild(codeElement);
const codeBlockDiv = document.createElement('div');
codeBlockDiv.classList.add('code-block');
codeBlockDiv.appendChild(pre);
output.appendChild(codeBlockDiv);
hljs.highlightElement(codeElement); // Highlight the code
terminal.scrollTop = output.scrollHeight;
};
// Displays a confirmation modal
const showConfirmModal = (message, callback) => {
confirmMessage.textContent = message;
confirmCallback = callback;
confirmModal.style.display = 'flex';
confirmYesBtn.focus(); // Focus on Yes button for quick action
};
// Command Implementations
const COMMANDS = {
help: () => appendLine(formatHelp([
["help", "Shows this message"],
["clear", "Clears the screen"],
["ls [-a]", "Lists files in the current directory"],
["cd [dir]", "Changes directory. Supports .., ~, /"],
["pwd", "Prints working directory"],
["touch [file]", "Creates an empty file"],
["cat [file]", "Displays file content with highlighting"],
["edit [file]", "Edits content of a file (opens modal)"],
["run [file]", "Simulates running a code file"],
["saveas <src> <dest>", "Saves content of <src> file to <dest>"],
["rm <file/dir>", "Removes a file or empty directory"],
["mkdir <dir>", "Creates a new directory"],
["mv <src> <dest>", "Moves or renames a file/directory"],
["grep <pattern> <file>", "Searches for a pattern in a file"], // New
["download <file>", "Downloads a file from the terminal"], // New
["init <type> [name]", "Initializes a new project boilerplate"], // New
["history", "Displays command history"],
["alias", "Manage command aliases"],
["theme [name]", "Changes the color theme"],
["neofetch", "Show system information"],
["man [cmd]", "Display manual page for a command"],
["@coder [q]", "Ask a programming question (uses Gemini Pro if available)"],
["@sysadmin [q]", "Ask a systems/DevOps question (uses Gemini)"],
["@git [q]", "Ask for a git command (uses Gemini)"],
["@designer [q]", "Ask a UI/UX or web design question (uses Gemini)"],
["@data [q]", "Ask a data analysis question (uses Gemini)"],
["@gen_code [q]", "Generate code snippet directly (uses Gemini Pro if available)"],
["@debug [file]", "Debugs code in a file (AI simulation)"],
["@refactor [file]", "Refactors code in a file (AI simulation)"],
["@test [file]", "Generates tests for code in a file (AI simulation)"],
["@explain_code [file]", "Explains code in a file (AI simulation)"], // New
["@lint_format [file]", "Suggests linting/formatting for code (AI sim)"], // New
["@chatgpt [q]", "Ask ChatGPT a question (simulated by Gemini)"],
["@grok [q]", "Ask Grok a question (simulated by Gemini)"],
["@deepseek [q]", "Ask DeepSeek a question (simulated by Gemini for code)"]
])),
clear: () => displayWelcomeMessage(),
pwd: () => appendLine(context.path),
ls: (args) => {
const node = getNode(context.path);
let children = node && node.children ? Object.keys(node.children) : [];
if (!args.includes('-a')) {
children = children.filter(c => !c.startsWith('.'));
}
appendLine(children.length > 0 ? children.map(c => getNode(context.path + '/' + c).type === 'dir' ? `<span class="prompt-path">${c}/</span>` : c).join(' ') : '');
},
cd: (args) => {
let target = args[0] || '~';
if(target === '~') target = HOME_DIR;
let newPath = target.startsWith('/') ? target : (context.path === '/' ? '' : context.path) + '/' + target;
let parts = newPath.split('/').reduce((acc, part) => {
if (part === '..') acc.pop();
else if (part !== '' && part !== '.') acc.push(part);
return acc;
}, []);
newPath = '/' + parts.join('/');
const targetNode = getNode(newPath);
if (targetNode && targetNode.type === 'dir') {
context.path = newPath;
const childrenNames = Object.keys(targetNode.children || {});
if(childrenNames.includes('package.json')) context.project_type = 'Node.js';
else if(childrenNames.includes('requirements.txt')) context.project_type = 'Python';
else if(childrenNames.includes('.git')) context.git_status = "On branch 'main', 2 changes."
else { context.project_type = 'Generic'; context.git_status = "Not a Git repository.";}
} else {
appendLine(`cd: no such file or directory: ${target}`, "color-error");
}
updatePrompt();
},
touch: (args) => {
if (!args[0]) { appendLine("touch: missing file operand", "color-error"); return; }
const { parentNode, name } = getParentNodeAndName(context.path + '/' + args[0]);
if (parentNode && parentNode.type === "dir" && !parentNode.children[name]) {
parentNode.children[name] = { type: 'file', content: '' };
appendLine(`File '${args[0]}' created.`, "color-system");
saveFS();
} else if (parentNode && parentNode.children[name]) {
appendLine(`File '${args[0]}' already exists.`, "color-warning");
} else {
appendLine(`touch: cannot create file '${args[0]}': No such file or directory`, "color-error");
}
},
cat: (args) => {
if (!args[0]) { appendLine("cat: missing file operand", "color-error"); return; }
const node = getNode(context.path + '/' + args[0]);
if(node && node.type === 'file') {
let language = 'plaintext';
if (args[0].endsWith('.js')) language = 'javascript';
else if (args[0].endsWith('.py')) language = 'python';
else if (args[0].endsWith('.html') || args[0].endsWith('.xml')) language = 'xml';
else if (args[0].endsWith('.css')) language = 'css';
else if (args[0].endsWith('.json')) language = 'json';
displayCode(node.content, language);
} else {
appendLine(`cat: ${args[0]}: No such file or directory`, "color-error");
}
},
edit: (args) => {
if (!args[0]) { appendLine("edit: missing file operand", "color-error"); return; }
const targetPath = context.path + '/' + args[0];
const node = getNode(targetPath);
if (node && node.type === 'file') {
currentEditFilePath = targetPath;
modalFileName.textContent = `Editing File: ${args[0]}`;
editTextArea.value = node.content;
editModal.style.display = 'flex'; // Show the modal
editTextArea.focus();
} else {
appendLine(`edit: ${args[0]}: No such file or directory or not a file`, "color-error");
}
},
run: async (args) => {
if (!args[0]) { appendLine("run: missing file operand", "color-error"); return; }
const targetPath = context.path + '/' + args[0];
const node = getNode(targetPath);
if (node && node.type === 'file') {
appendLine(`Simulating execution of '${args[0]}' in ${context.project_type} environment...`, "color-system");
const codeToRun = node.content;
const promptForRun = `Simulate running the following code in a ${context.project_type} environment and provide its console output. ONLY output the console output. Do NOT include any explanations or markdown.\n\nCode:\n${codeToRun}`;
const response = await callAIAPI(promptForRun, GEMINI_PROMPTS.code_runner, 'gemini-1.5-pro', 'gemini-pro');
if (response) {
appendLine(`--- Simulated Output for '${args[0]}' ---`, 'color-system');
displayCode(response, 'bash');
appendLine(`--- End Simulated Output ---`, 'color-system');
} else {
appendLine(`Failed to simulate execution for '${args[0]}'.`, "color-error");
}
} else {
appendLine(`run: ${args[0]}: No such file or directory or not a file`, "color-error");
}
},
saveas: (args) => {
if (args.length !== 2) { appendLine("Usage: saveas <source_file> <destination_file>", "color-error"); return; }
const sourcePath = context.path + '/' + args[0];
const destPath = context.path + '/' + args[1];
const sourceNode = getNode(sourcePath);
if (!sourceNode || sourceNode.type !== 'file') {
appendLine(`saveas: source file not found or not a file: ${args[0]}`, "color-error");
return;
}
const { parentNode: destParentNode, name: destName } = getParentNodeAndName(destPath);
if (!destParentNode || destParentNode.type !== 'dir') {
appendLine(`saveas: destination directory not found: ${args[1]}`, "color-error");
return;
}
if (destParentNode.children[destName]) {
appendLine(`saveas: destination file already exists: ${args[1]}`, "color-warning");
// Optionally ask for overwrite confirmation
}
destParentNode.children[destName] = { type: 'file', content: sourceNode.content };
appendLine(`File '${args[0]}' saved as '${args[1]}'.`, "color-system");
saveFS();
},
rm: (args) => {
if (!args[0]) { appendLine("rm: missing operand", "color-error"); return; }
const targetPath = context.path + '/' + args[0];
const node = getNode(targetPath);
if (!node) {
appendLine(`rm: cannot remove '${args[0]}': No such file or directory`, "color-error");
return;
}
if (node.type === 'dir' && Object.keys(node.children).length > 0) {
appendLine(`rm: cannot remove '${args[0]}': Directory not empty`, "color-error");
appendLine("Use 'rm -r' to remove non-empty directories (not implemented in simulation).", "color-warning");
return;
}
showConfirmModal(`Are you sure you want to remove '${args[0]}'?`, (confirmed) => {
if (confirmed) {
const { parentNode, name } = getParentNodeAndName(targetPath);
if (parentNode && parentNode.children) {
delete parentNode.children[name];
appendLine(`Removed '${args[0]}'.`, "color-system");
saveFS();
}
} else {
appendLine("Removal cancelled.", "color-warning");
}
commandInput.focus(); // Restore focus
});
},
mkdir: (args) => {
if (!args[0]) { appendLine("mkdir: missing operand", "color-error"); return; }
const targetPath = context.path + '/' + args[0];
const { parentNode, name } = getParentNodeAndName(targetPath);
if (!parentNode || parentNode.type !== 'dir') {
appendLine(`mkdir: cannot create directory '${args[0]}': No such file or directory`, "color-error");
return;
}
if (parentNode.children[name]) {
appendLine(`mkdir: cannot create directory '${args[0]}': File exists`, "color-error");
return;
}
parentNode.children[name] = { type: 'dir', children: {} };
appendLine(`Directory '${args[0]}' created.`, "color-system");
saveFS();
},
mv: (args) => {
if (args.length !== 2) { appendLine("Usage: mv <source> <destination>", "color-error"); return; }
const sourcePath = context.path + '/' + args[0];
const destPath = context.path + '/' + args[1];
const sourceNode = getNode(sourcePath);
if (!sourceNode) {
appendLine(`mv: cannot stat '${args[0]}': No such file or directory`, "color-error");
return;
}
const { parentNode: sourceParentNode, name: sourceName } = getParentNodeAndName(sourcePath);
const { parentNode: destParentNode, name: destName } = getParentNodeAndName(destPath);
// Handle rename within same directory or move to new directory
if (destParentNode && destParentNode.type === 'dir') {
if (destParentNode.children[destName]) {
appendLine(`mv: cannot overwrite existing '${args[1]}'`, "color-error");
return;
}
destParentNode.children[destName] = sourceNode;
delete sourceParentNode.children[sourceName];
appendLine(`Moved '${args[0]}' to '${args[1]}'.`, "color-system");
saveFS();
} else {
appendLine(`mv: cannot move to '${args[1]}': No such file or directory`, "color-error");
}
},
grep: (args) => {
if (args.length !== 2) { appendLine("Usage: grep <pattern> <file>", "color-error"); return; }
const pattern = new RegExp(args[0], 'g'); // Global search
const filePath = context.path + '/' + args[1];
const fileNode = getNode(filePath);
if (!fileNode || fileNode.type !== 'file') {
appendLine(`grep: ${args[1]}: No such file or not a file`, "color-error");
return;
}
const lines = fileNode.content.split('\n');
let foundMatches = false;
lines.forEach((line, index) => {
if (line.match(pattern)) {
foundMatches = true;
const highlightedLine = line.replace(pattern, (match) => `<span class="grep-match">${match}</span>`);
appendLine(`<span class="grep-line">${filePath}:${index + 1}: ${highlightedLine}</span>`);
}
});
if (!foundMatches) {
appendLine(`No matches found for '${args[0]}' in '${args[1]}'.`, "color-system");
}
},
download: (args) => {
if (!args[0]) { appendLine("download: missing file operand", "color-error"); return; }
const filePath = context.path + '/' + args[0];
const fileNode = getNode(filePath);
if (!fileNode || fileNode.type !== 'file') {
appendLine(`download: ${args[0]}: No such file or not a file`, "color-error");
return;
}
const fileName = args[0].split('/').pop(); // Get just the file name
const blob = new Blob([fileNode.content], { type: 'text/plain' }); // Default to text/plain
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a); // Append to body to make it clickable
a.click();
document.body.removeChild(a); // Clean up
URL.revokeObjectURL(url); // Release the URL object
appendLine(`Downloading '${fileName}'...`, "color-system");
},
init: (args) => {
if (args.length < 1 || args.length > 2) { appendLine("Usage: init <project_type> [name]", "color-error"); return; }
const projectType = args[0].toLowerCase();
const projectName = args[1] || `${projectType}-project`;
const projectPath = context.path + '/' + projectName;
if (getNode(projectPath)) {
appendLine(`init: directory '${projectName}' already exists.`, "color-error");
return;
}
// Call AI to generate boilerplate
appendLine(`Initializing new '${projectType}' project as '${projectName}'...`, "color-system");
const prompt = `Generate boilerplate for a new '${projectType}' project named '${projectName}'. Provide touch and echo commands for creating files and their content. If 'web-app', include index.html, style.css, script.js. If 'python-app', include main.py, requirements.txt.`;
callAIAPI(prompt, GEMINI_PROMPTS.project_initializer, 'gemini-1.5-pro', 'gemini-pro')
.then(response => {
if (response) {
appendLine(`AI's Initialization Plan:`, 'color-ai');
// Split AI's response into lines and execute commands
const commands = response.split('\n').filter(line => line.trim().startsWith('touch') || line.trim().startsWith('echo'));
commands.forEach(cmdLine => {
if (cmdLine.startsWith('touch ')) {
const filePath = cmdLine.substring(6).trim(); // Remove 'touch '
getNode(projectPath + '/' + filePath, true, 'file'); // Create the file
appendLine(`Created: ${projectPath + '/' + filePath}`, 'color-system');
} else if (cmdLine.startsWith('echo ')) {
const match = cmdLine.match(/echo "(.*?)" > (.*)/);
if (match) {
const content = match[1].replace(/\\n/g, '\n'); // Handle escaped newlines
const filePath = match[2].trim();
const fileNode = getNode(projectPath + '/' + filePath);
if (fileNode && fileNode.type === 'file') {
fileNode.content = content;
appendLine(`Populated: ${projectPath + '/' + filePath}`, 'color-system');
} else {
appendLine(`Error: Could not populate ${projectPath + '/' + filePath}. File not found or not created by touch.`, 'color-error');
}
}
}
});
saveFS(); // Save the new project structure
} else {
appendLine(`AI failed to generate initialization boilerplate.`, "color-error");
}
});
},
history: () => {
if (commandHistory.length === 0) {
appendLine("No command history yet.", "color-system");
return;
}
commandHistory.forEach((cmd, index) => {
appendLine(`${String(commandHistory.length - index).padStart(4, ' ')} ${cmd}`);
});
},
theme: (args) => {
const themeName = args[0];
if (THEMES[themeName]) {
Object.entries(THEMES[themeName]).forEach(([key, value]) => root.style.setProperty(key, value));
appendLine(`Theme changed to <span class="color-ai">${themeName}</span>.`, "color-system");
} else {
appendLine(`Theme not found. Available themes: ${Object.keys(THEMES).join(', ')}`, "color-error");
}
},
alias: (args) => {
if (args.length === 0) {
Object.entries(aliases).forEach(([name, cmd]) => appendLine(`alias ${name}='${cmd}'`));
return;
}
const declaration = args.join(' ');
const match = declaration.match(/^([a-zA-Z0-9]+)='(.*?)'$/);
if(match) {
aliases[match[1]] = match[2];
appendLine(`Alias created: ${match[1]} -> ${match[2]}`, 'color-system');
} else {
appendLine(`Usage: alias [name]='[command]'`, 'color-error');
}
},
neofetch: () => {
appendLine(`
<span class="prompt-user">user@aetherius</span>
------------------
<span class="color-system">OS</span>: Aetherius Terminal v3 (Web)
<span class="color-system">Host</span>: Your Browser
<span class="color-system">Kernel</span>: JavaScript
<span class="color-system">Uptime</span>: since page load
<span class="color-system">Shell</span>: aetherius.js
<span class="color-system">AI Model (Gemini)</span>: ${API_KEYS['gemini'] ? 'gemini-1.5-flash' : 'N/A'}
<span class="color-system">AI Model (Gemini Pro)</span>: ${API_KEYS['gemini-pro'] ? 'gemini-1.5-pro' : 'N/A'}
<span class="color-system">AI Model (ChatGPT)</span>: ${API_KEYS['chatgpt'] ? 'Simulated' : 'N/A'}
<span class="color-system">AI Model (Grok)</span>: ${API_KEYS['grok'] ? 'Simulated' : 'N/A'}
<span class="color-system">AI Model (DeepSeek)</span>: ${API_KEYS['deepseek'] ? 'Simulated' : 'N/A'}
`);
},
man: (args) => {
appendLine(`Manual for <span class='color-ai'>${args[0]}</span>:\nNo detailed manual pages yet. Try 'help'.`, 'color-system')
},
};
// --- 5. Main Execution Loop ---
const processCommand = async (commandStr) => {
appendLine(`<span id="prompt-context">${promptContext.innerHTML}</span><span class="prompt-arrow">></span> ${commandStr}`, "");
if(commandStr) {
commandHistory = commandHistory.filter(c => c !== commandStr);
commandHistory.unshift(commandStr);
if(commandHistory.length > 50) commandHistory.pop();
}
historyIndex = -1;
let [cmd, ...args] = commandStr.trim().split(/\s+/);
if (!cmd) return;
// Alias replacement
if (aliases[cmd]) {
const aliasedCommand = aliases[cmd];
appendLine(`~ executing alias: <span class="color-ai">${aliasedCommand}</span>`, 'color-system');
[cmd, ...args] = aliasedCommand.trim().split(/\s+/);
}
if (cmd.startsWith('@')) {
const agent = cmd.toLowerCase();
let promptKey;
let modelToUse = 'gemini-1.5-flash'; // Default model
let apiIdToUse = 'gemini'; // Default API ID
let fileContentForAI = null; // Used for agents that read file content
switch(agent) {
case '@coder':
promptKey = 'coder';
if (API_KEYS['gemini-pro']) {
modelToUse = 'gemini-1.5-pro';
apiIdToUse = 'gemini-pro';
}
break;
case '@sysadmin':
promptKey = 'sysadmin';
break;
case '@git':
promptKey = 'git';
break;
case '@designer':
promptKey = 'designer';
break;
case '@data':
promptKey = 'data';
break;
case '@gen_code':
promptKey = 'code_generator';
if (API_KEYS['gemini-pro']) {
modelToUse = 'gemini-1.5-pro';
apiIdToUse = 'gemini-pro';
}
break;
case '@debug':
case '@refactor':
case '@test':
case '@explain_code': // New agent
case '@lint_format': // New agent
if (!args[0]) { appendLine(`${agent}: missing file operand. Usage: ${agent} <file>`, "color-error"); return; }
const fileNode = getNode(context.path + '/' + args[0]);
if (!fileNode || fileNode.type !== 'file') {
appendLine(`${agent}: ${args[0]}: No such file or not a file`, "color-error");
return;
}
fileContentForAI = fileNode.content; // Capture file content
if (API_KEYS['gemini-pro']) { // These agents benefit from Pro model
modelToUse = 'gemini-1.5-pro';
apiIdToUse = 'gemini-pro';
}
if (agent === '@debug') promptKey = 'debugger';
else if (agent === '@refactor') promptKey = 'refactorer';
else if (agent === '@test') promptKey = 'tester';
else if (agent === '@explain_code') promptKey = 'code_explainer';
else if (agent === '@lint_format') promptKey = 'linter_formatter';
// Modify prompt for these agents to include file content
args = [`${args.join(' ')}\n\nCode from ${args[0]} (Type: ${context.project_type}):\n\n\`\`\`${fileContentForAI}\`\`\``];
break;
case '@chatgpt':
promptKey = 'chatgpt';
apiIdToUse = 'chatgpt';
break;
case '@grok':
promptKey = 'grok';
apiIdToUse = 'grok';
break;
case '@deepseek':
promptKey = 'deepseek';
apiIdToUse = 'deepseek';
if (API_KEYS['gemini-pro']) {
modelToUse = 'gemini-1.5-pro';
}
break;
default:
appendLine(`Unknown agent: ${agent}`, "color-error");
return;
}
appendLine(`Querying <span class="color-agent-name">${agent}</span> agent (using ${apiIdToUse} - simulated by Gemini)...`, 'color-system');
// Note: callAIAPI handles API Key prioritization and fallback internally
const response = await callAIAPI(args.join(' '), GEMINI_PROMPTS[promptKey], modelToUse, apiIdToUse);
if(response) {
// Determine if response is a code block and highlight it
const codeBlockMatch = response.match(/```(.*?)```/gs);
if (codeBlockMatch) {
const codeContent = codeBlockMatch[0].replace(/```(.*)?\n/, '').replace(/```$/, '').trim();
let language = 'plaintext';
const langMatch = codeBlockMatch[0].match(/```(\w+)\n/);
if (langMatch && hljs.getLanguage(langMatch[1])) {
language = langMatch[1];
} else { // Fallback based on common coding contexts
if (agent === '@coder' || agent === '@gen_code' || agent === '@deepseek' || context.project_type === 'Python') {
language = 'python';
} else if (context.project_type === 'Node.js') {
language = 'javascript';
} else if (agent === '@designer') {
language = 'xml'; // For HTML
}
}
// Display non-code parts if any
const preCodeText = response.substring(0, response.indexOf(codeBlockMatch[0])).trim();
if (preCodeText) appendLine(preCodeText, 'color-ai');
displayCode(codeContent, language);
const postCodeText = response.substring(response.indexOf(codeBlockMatch[0]) + codeBlockMatch[0].length).trim();
if (postCodeText) appendLine(postCodeText, 'color-ai');
} else {
appendLine(response, 'color-ai'); // Display as plain text if no code block
}
}
} else if (COMMANDS[cmd]) {
COMMANDS[cmd](args);
} else {
// If command is not a built-in command and not an explicit AI agent, attempt code generation
appendLine("Command not recognized. Attempting to send as code generation request to AI...", 'color-system');
const codeResponse = await callAIAPI(commandStr, GEMINI_PROMPTS.code_generator, 'gemini-1.5-pro', 'gemini-pro');
if (codeResponse) {
const codeBlockMatch = codeResponse.match(/```(.*?)```/gs);
if (codeBlockMatch) {
const codeContent = codeBlockMatch[0].replace(/```(.*)?\n/, '').replace(/```$/, '').trim();
let language = 'plaintext';
const langMatch = codeBlockMatch[0].match(/```(\w+)\n/);
if (langMatch && hljs.getLanguage(langMatch[1])) {
language = langMatch[1];
} else { // Fallback based on common coding contexts
if (context.project_type === 'Python') {
language = 'python';
} else if (context.project_type === 'Node.js') {
language = 'javascript';
} else {
language = 'plaintext';
}
}
appendLine(`AI auto-generated code:`, 'color-ai');
displayCode(codeContent, language);
appendLine(`You can try to 'edit [filename]' to save it, then 'run [filename]' to simulate execution.`, 'color-system');
} else {
// If AI did not generate a code block, fall back to trying command translation
appendLine(`AI did not directly generate code. Attempting as command translation request...`, 'color-system');
const proposedCommand = await callAIAPI(commandStr, GEMINI_PROMPTS.command_translator, 'gemini-1.5-flash', 'gemini');
if (proposedCommand) {
if (proposedCommand === 'AETHERIUS_CANNOT_TRANSLATE') {
appendLine("Could not translate to command or generate code. For general questions, try agents like <span class='color-ai'>@coder</span>.", 'color-warning');
} else {
appendLine(`AI Suggestion:<div class="color-suggestion">${proposedCommand}</div>(This is a <span class="color-warning">simulation</span>. No real commands are executed.)`, 'color-system');
}
} else {
appendLine("AI failed to respond to your request.", "color-error");
}
}
} else {
appendLine("AI failed to generate a response.", "color-error");
}
}
};
// --- 6. Event Listeners ---
// API Key panel toggle functionality
apiKeyHeader.addEventListener('click', () => {
if (apiKeyPanelContent.style.display === 'none' || apiKeyPanelContent.style.display === '') {
apiKeyPanelContent.style.display = 'flex';
apiKeyToggleIcon.textContent = '▼';
localStorage.setItem('api_key_panel_expanded', 'true');
} else {
apiKeyPanelContent.style.display = 'none';
apiKeyToggleIcon.textContent = '▲';
localStorage.setItem('api_key_panel_expanded', 'false');
}
});
// Add event listeners for all save buttons
apiKeySaveBtns.forEach(button => {
button.addEventListener('click', () => {
const apiId = button.dataset.apiId;
const keyInputId = `${apiId}-api-key-input`;
const statusElementId = `${apiId}-api-key-status`;
saveApiKey(apiId, keyInputId, statusElementId);
});
});
// Add Enter key listener for all API Key input fields
document.querySelectorAll('.api-key-item input[type="password"]').forEach(input => {
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
const apiId = e.target.id.replace('-api-key-input', '');
const keyInputId = e.target.id;
const statusElementId = `${apiId}-api-key-status`;
saveApiKey(apiId, keyInputId, statusElementId);
}
});
});
// Edit Modal Event Listeners
saveEditBtn.addEventListener('click', () => {
if (currentEditFilePath) {
const { parentNode, name } = getParentNodeAndName(currentEditFilePath);
if (parentNode && parentNode.children && parentNode.children[name]) {
parentNode.children[name].content = editTextArea.value;
appendLine(`File '${name}' saved successfully.`, "color-system");
saveFS(); // Save FS after editing
}
editModal.style.display = 'none'; // Hide the modal
currentEditFilePath = null;
commandInput.focus(); // Return focus to command input
}
});
cancelEditBtn.addEventListener('click', () => {
editModal.style.display = 'none'; // Hide the modal
currentEditFilePath = null;
appendLine(`Edit cancelled.`, "color-warning");
commandInput.focus(); // Return focus to command input
});
// Allow Tab key within textarea for actual indentation
editTextArea.addEventListener('keydown', (e) => {
if (e.key === 'Tab') {
e.preventDefault();
const start = editTextArea.selectionStart;
const end = editTextArea.selectionEnd;
const value = editTextArea.value;
editTextArea.value = value.substring(0, start) + '\t' + value.substring(end);
editTextArea.selectionStart = editTextArea.selectionEnd = start + 1;
}
});
// Confirmation Modal Event Listeners
confirmYesBtn.addEventListener('click', () => {
if (confirmCallback) {
confirmCallback(true);
}
confirmModal.style.display = 'none';
confirmCallback = null;
});
confirmNoBtn.addEventListener('click', () => {
if (confirmCallback) {
confirmCallback(false);
}
confirmModal.style.display = 'none';
confirmCallback = null;
});
commandInput.addEventListener('keydown', (e) => {
const handleKeyDown = {
'Enter': () => {
if(commandInput.value.trim() !== ''){
e.preventDefault();
processCommand(commandInput.value);
commandInput.value = '';
}
},
'ArrowUp': () => {
e.preventDefault();
if (historyIndex < commandHistory.length - 1) {
historyIndex++;
commandInput.value = commandHistory[historyIndex];
}
},
'ArrowDown': () => {
e.preventDefault();
if (historyIndex > 0) {
historyIndex--;
commandInput.value = commandHistory[historyIndex];
} else {
historyIndex = -1;
commandInput.value = '';
}
},
'Tab': (event) => {
event.preventDefault(); // Prevent default tab behavior
const text = commandInput.value;
const node = getNode(context.path);
const fileItems = node && node.children ? Object.keys(node.children) : [];
// Include all agent commands and new commands for autocompletion
const allCompletions = [...Object.keys(COMMANDS), ...Object.keys(aliases), ...fileItems, ...Object.keys(THEMES),
'@coder', '@sysadmin', '@git', '@designer', '@data', '@gen_code', '@debug', '@refactor', '@test', '@explain_code', '@lint_format', '@chatgpt', '@grok', '@deepseek'];
const matches = allCompletions.filter(item => item.startsWith(text));
if (matches.length === 1) {
commandInput.value = matches[0] + ' ';
} else if (matches.length > 1) {
appendLine(matches.join(' '), 'color-ai');
}
}
};
if (handleKeyDown[e.key]) handleKeyDown[e.key]();
});
terminal.addEventListener('click', (e) => {
// Don't steal focus from text selection
if(window.getSelection().toString() === ''){
commandInput.focus()
}
});
// --- 7. App Initialization ---
buildFS(); // Load or build filesystem
displayWelcomeMessage();
updatePrompt();
// Restore API Key panel state
const panelExpanded = localStorage.getItem('api_key_panel_expanded');
if (panelExpanded === 'false') {
apiKeyPanelContent.style.display = 'none';
apiKeyToggleIcon.textContent = '▲';
} else {
apiKeyPanelContent.style.display = 'flex';
apiKeyToggleIcon.textContent = '▼';
}
// Attempt to focus on the command input field on initial load
commandInput.focus();
});
</script>
</body>
</html>