"use strict"; const https = require("https"); const crypto = require("crypto"); const FormData = require("form-data"); const { createDashboardAssistantHistory } = require("../services/dashboard-assistant-history"); const { TOOL_DEFINITIONS, POWER_TOOL_NAMES, POWER_TOOL_DEFINITIONS, buildSystemPrompt, createDashboardAssistantToolRunner, } = require("./dashboard-assistant-tools"); const DEFAULT_CHAT_TITLE = "ADPanel Assistant"; const DEFAULT_GROQ_MODEL = process.env.DASHBOARD_ASSISTANT_GROQ_MODEL || "openai/gpt-oss-120b"; const DEFAULT_GROQ_TRANSCRIPTION_MODEL = process.env.DASHBOARD_ASSISTANT_GROQ_STT_MODEL || "whisper-large-v3"; const DEFAULT_GOOGLE_MODEL = process.env.DASHBOARD_ASSISTANT_GOOGLE_MODEL || "gemini-2.5-flash-lite"; const DEFAULT_GOOGLE_TRANSCRIPTION_MODEL = process.env.DASHBOARD_ASSISTANT_GOOGLE_STT_MODEL || "gemini-2.5-flash"; const VISIBLE_CHAT_HISTORY_LIMIT = 80; const CHAT_HISTORY_LIMIT = VISIBLE_CHAT_HISTORY_LIMIT; const MAX_CHAT_MESSAGES = VISIBLE_CHAT_HISTORY_LIMIT; const MODEL_CONTEXT_RECENT_MESSAGE_LIMIT = 16; const MODEL_CONTEXT_RECENT_MESSAGE_CHAR_LIMIT = 520; const MODEL_CONTEXT_NEAR_MESSAGE_CHAR_LIMIT = 760; const MODEL_CONTEXT_LATEST_MESSAGE_CHAR_LIMIT = 1400; const MODEL_CONTEXT_OLDER_TRANSCRIPT_COUNT = 10; const MODEL_CONTEXT_OLDER_TRANSCRIPT_TOTAL_LIMIT = 1400; // Persisted chat input caps. Chat content is stored in LONGTEXT with no // schema-side bound, so without these a single account could persist // gigabytes per day (1 MB body limit x the completion rate limiter). 8000 // chars is ~5x the tightest prompt-side compaction // (MODEL_CONTEXT_LATEST_MESSAGE_CHAR_LIMIT = 1400): real questions fit far // below it, and model context is re-compacted per turn regardless. const ASSISTANT_USER_MESSAGE_MAX_CHARS = 8000; // /client-follow-up summaries are short verified-result recaps (the AI reply // for them is capped at max_tokens 700), so 2000 is generous headroom. const ASSISTANT_FOLLOWUP_SUMMARY_MAX_CHARS = 2000; // context is prompt-only (never persisted); naming the existing slice bound // keeps it discoverable next to the other input caps. const ASSISTANT_FOLLOWUP_CONTEXT_MAX_CHARS = 4000; // sourceType is prompt-embedded only (never persisted); slice-capped like context. const ASSISTANT_FOLLOWUP_SOURCETYPE_MAX_CHARS = 200; const ACCESSIBLE_SERVERS_CACHE_TTL_MS = 15_000; // Hard ceiling on how long the decrypted provider-secret cache may live // without a reload. The primary invalidation signal is the .env mtime (see // ensureProviderSecretCache), but a same-tick write that mtime granularity // cannot distinguish, or a dep that cannot stat at all, must never pin a // rotated/revoked key longer than this. const PROVIDER_SECRET_CACHE_REVALIDATE_TTL_MS = 5 * 60 * 1000; const ASSISTANT_MAX_LOOPS = 6; const AUDIO_UPLOAD_LIMIT_BYTES = parseInt(process.env.DASHBOARD_ASSISTANT_AUDIO_LIMIT_BYTES || "", 10) || 15 * 1024 * 1024; // Ceiling on provider response bytes for jsonApiRequest/groqMultipartRequest. // Both target hardcoded Groq/Google hosts, but a misbehaving provider or a // TLS-intercepting middlebox can still stream an unbounded body, and these // helpers are the last uncapped byte-accumulator in the assistant path // (uploads, prompts and the index.js raw fetch all bound theirs) — without a // ceiling a hostile body OOMs the pm2 worker. Real payloads (JSON chat, // model-list and transcription replies) peak in the low MBs, so 20 MiB is // runaway-guard headroom, not an operating point. const ASSISTANT_PROVIDER_RESPONSE_MAX_BYTES = (() => { const parsed = parseInt(process.env.DASHBOARD_ASSISTANT_PROVIDER_RESPONSE_MAX_BYTES || "", 10); return Number.isInteger(parsed) && parsed >= 1 ? parsed : 20 * 1024 * 1024; })(); const GOOGLE_OPENAI_CHAT_URL = "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"; const GOOGLE_INTERACTIONS_URL = "https://generativelanguage.googleapis.com/v1beta/interactions"; const GOOGLE_MODELS_LIST_URL = "https://generativelanguage.googleapis.com/v1beta/models"; const GROQ_MODELS_LIST_URL = "https://api.groq.com/openai/v1/models"; const POWER_ONLY_ASSISTANT = true; // Dashboard assistant delete flow. The pending intent is real server-side // state: a short-TTL, single-use, session-scoped record // (req.session.assistantDeleteIntents) plus an HMAC action token bound to the // exact intent/chat/server triple and to the admin's session. Tokens are // minted ONLY by createDeleteIntent/mintDeleteIntent, and only after the // request_delete_server tool has validated an admin, a chat this user owns, // and a server that exists — so a bare admin session (or XSS) holds no // standing "delete anything" capability: every confirm needs a live intent, // its single-use token, and the same credential step-up as the admin delete // route. const DELETE_INTENT_TTL_MS = 2 * 60 * 1000; const DELETE_INTENT_MAX_PENDING_PER_SESSION = 3; const ASSISTANT_DELETE_CONFIRM_ACTION = "POST /api/dashboard-assistant/confirm-delete"; function formatModelDisplayName(rawModelId) { if (!rawModelId) return ""; let name = String(rawModelId).replace(/^models\//i, "").trim(); const knownMap = { "llama-3.1-8b-instant": "Llama 3.1 8B", "llama-3.3-70b-versatile": "Llama 3.3 70B", "llama-3.1-70b-versatile": "Llama 3.1 70B", "llama3-8b-8192": "Llama 3 8B", "llama3-70b-8192": "Llama 3 70B", "qwen-2.5-coder-32b": "Qwen 2.5 Coder 32B", "deepseek-r1-distill-llama-70b": "DeepSeek R1 Distill 70B", "mixtral-8x7b-32768": "Mixtral 8x7B", "gemma2-9b-it": "Gemma 2 9B", "openai/gpt-oss-120b": "GPT-OSS 120B", "openai/gpt-oss-20b": "GPT-OSS 20B", "qwen/qwen3.8-27b": "Qwen 3.8 27B", "allam-2-7b": "ALLAM 2 7B", "gemini-2.5-flash": "Gemini 2.5 Flash", "gemini-2.5-flash-lite": "Gemini 2.5 Flash Lite", "gemini-2.5-pro": "Gemini 2.5 Pro", "gemini-1.5-flash": "Gemini 1.5 Flash", "gemini-1.5-pro": "Gemini 1.5 Pro", "gemini-2.0-flash": "Gemini 2.0 Flash" }; if (knownMap[name.toLowerCase()]) { return knownMap[name.toLowerCase()]; } name = name .replace(/-(instant|versatile|32768|it|latest|preview)$/i, "") .replace(/-/g, " ") .replace(/\b\w/g, char => char.toUpperCase()); return name; } const DEFAULT_MODELS = Object.freeze({ groq: [ { value: "openai/gpt-oss-120b", label: "GPT-OSS 120B" }, { value: "openai/gpt-oss-20b", label: "GPT-OSS 20B" }, { value: "qwen/qwen3.8-27b", label: "Qwen 3.8 27B" }, { value: "allam-2-7b", label: "ALLAM 2 7B" } ], google: [ { value: "gemini-2.5-flash-lite", label: "Gemini 2.5 Flash Lite" }, { value: "gemini-2.5-flash", label: "Gemini 2.5 Flash" }, { value: "gemini-2.5-pro", label: "Gemini 2.5 Pro" }, { value: "gemini-2.0-flash", label: "Gemini 2.0 Flash" } ] }); // Provider model lineups rotate without notice (Groq retired // llama-3.1-8b-instant outright), so chat always runs on a model confirmed to // exist in the provider's live model list. The preference list is only the // pick order within whatever the provider currently offers: missing ids are // skipped, and the first live chat-capable model is the final fallback. const CHAT_MODEL_PREFERENCES = Object.freeze({ groq: Object.freeze([ "openai/gpt-oss-120b", "openai/gpt-oss-20b", "qwen/qwen3.8-27b", "allam-2-7b", "llama-3.3-70b-versatile", "llama-3.1-8b-instant", ]), google: Object.freeze([ "gemini-2.5-flash-lite", "gemini-2.5-flash", "gemini-2.0-flash", "gemini-2.5-pro", ]), }); // Client-picked chat models ("Select your intelligence" dropdown) are // attacker-controlled input: before such a value may reach // requestChatCompletion it must pass this shape check AND be allowlisted // against the provider's live chat-capable model list (the same list the // /models endpoint serves). Anything else falls through to the server-side // resolution order — no client string is ever passed to a provider as-is. const REQUESTED_MODEL_MAX_LENGTH = 128; const REQUESTED_MODEL_PATTERN = /^[A-Za-z0-9._/-]+$/; const MODEL_OVERRIDE_ENV_KEYS = Object.freeze({ groq: "DASHBOARD_ASSISTANT_GROQ_MODEL", google: "DASHBOARD_ASSISTANT_GOOGLE_MODEL", }); const PROVIDER_MODELS_CACHE_TTL_MS = 10 * 60 * 1000; const PROVIDER_MODELS_ERROR_TTL_MS = 60 * 1000; function isChatCapableGroqModelId(modelId) { // Groq's model list mixes in STT/TTS/safety models that cannot chat. return !/whisper|guard|tts|orpheus|playai|embed|distil|gaze|\basr\b|\bstt\b/i.test(modelId); } function isChatCapableGoogleModelId(modelId, methods) { if (!/^gemini/i.test(modelId)) return false; if (!Array.isArray(methods) || !methods.includes("generateContent")) return false; return !/tts|image|audio|embedding|imagen|veo|live|transcribe|speech/i.test(modelId); } async function fetchProviderChatModelIds(provider, apiKey) { if (provider === "google") { const response = await jsonApiRequest(GOOGLE_MODELS_LIST_URL, { method: "GET", headers: { "x-goog-api-key": apiKey }, agent: ASSISTANT_PROVIDER_HTTPS_AGENTS.google, timeoutMs: 10_000, timeoutMessage: "Google AI Studio models request timeout", }); if (response.status !== 200) { throw new Error(`Google AI Studio model list failed (status ${response.status}).`); } return (Array.isArray(response.data?.models) ? response.data.models : []) .map((model) => ({ id: String(model?.name || "").replace(/^models\//i, "").trim(), methods: model?.supportedGenerationMethods, })) .filter((model) => model.id && isChatCapableGoogleModelId(model.id, model.methods)) .map((model) => model.id) .sort(); } const response = await jsonApiRequest(GROQ_MODELS_LIST_URL, { method: "GET", headers: { Authorization: `Bearer ${apiKey}` }, agent: ASSISTANT_PROVIDER_HTTPS_AGENTS.groq, timeoutMs: 10_000, timeoutMessage: "Groq models request timeout", }); if (response.status !== 200) { throw new Error(`Groq model list failed (status ${response.status}).`); } return (Array.isArray(response.data?.data) ? response.data.data : []) .map((model) => (model?.active === false ? "" : String(model?.id || "").trim())) .filter((modelId) => modelId && isChatCapableGroqModelId(modelId)) .sort(); } const PROVIDER_LABELS = Object.freeze({ groq: "Groq", google: "Google AI Studio", }); const SUPPORTED_PROVIDERS = new Set(Object.keys(PROVIDER_LABELS)); const ASSISTANT_PROVIDER_SECRET_ENV_KEYS = Object.freeze({ groq: { encrypted: "DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED", legacy: ["GROQ_API_KEY"], // Ownership split: GROQ_API_KEY is co-owned by the /api/ai/keys provider // settings feature (its primary .env storage), so purging it here would // strand that feature after a restart — it stays in `legacy` only. legacyPurgeable: [], }, google: { encrypted: "DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ENCRYPTED", legacy: ["GOOGLE_AI_STUDIO_API_KEY", "GOOGLE_AI_KEY"], // GOOGLE_AI_STUDIO_API_KEY is consumed only by this assistant's legacy // plaintext fallback, so it is safe to purge from .env once the key is // stored encrypted. GOOGLE_AI_KEY is co-owned by /api/ai/keys and must // never be purged by the assistant. legacyPurgeable: ["GOOGLE_AI_STUDIO_API_KEY"], }, }); const ASSISTANT_PROVIDER_SECRET_VERSION = "enc-v1"; const ASSISTANT_PROVIDER_SECRET_VERSION_V2 = "enc-v2"; const ASSISTANT_PROVIDER_SECRET_CONTEXT = "adpanel:dashboard-assistant:provider-key:v1"; // Quarantine (recovery) slots for the enc-v1 migration, named after the // provider's live encrypted key + "_ORPHANED_V1". When an enc-v1 value's // minting secret was lost or rotated away, the value can never decrypt again // and would otherwise sit in its LIVE slot forever, holding SECRET_KEY in the // decryption chain and keeping the weak legacy state alive. After the failure // is proven persistent (see ASSISTANT_PROVIDER_SECRET_QUARANTINE_THRESHOLD), // migrateAssistantProviderSecretsV1ToV2 MOVES such a value here — quarantine, // never destruction: the slot is a manual recovery artifact for an operator // who recovers the lost secret (decrypt the stored envelope with it) and is // safe to delete otherwise. These keys are never read by any runtime path, // never overwritten while occupied (an existing artifact is absolute), and // only ever written to an EMPTY slot through the verified batch writer. const ASSISTANT_PROVIDER_SECRET_ORPHANED_V1_ENV_KEYS = Object.freeze({ groq: "DASHBOARD_ASSISTANT_GROQ_API_KEY_ORPHANED_V1", google: "DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ORPHANED_V1", }); // Legacy single-secret chain, kept as the ordered candidate list for enc-v1 // decryption. SECRET_KEY is the reCAPTCHA site secret that Google also holds, // so it stays a decrypt-only last resort and never mints new values — and it // is a stop-gap only: the startup migration // (migrateAssistantProviderSecretsV1ToV2) re-wraps every enc-v1 value into // enc-v2 under the dedicated secret and, once .env holds no enc-v1 values, // retires SECRET_KEY from this chain for the rest of the process // (assistantProviderSecretV1Retired). A failed or partial migration leaves // the full chain — and the flag — untouched; the migration retry scheduler // then keeps re-running the migration in this process with backoff until // retirement is confirmed (and every fresh boot starts a migration too). // A value whose minting secret is LOST can hold retirement hostage forever; // once its decryption failure is proven persistent across runs, the migration // QUARANTINES it into the provider's *_ORPHANED_V1 recovery slot above — // never destroying it — which empties the live slot so the legacy chain can // finally retire. const ASSISTANT_PROVIDER_SECRET_LEGACY_ENV_KEYS = Object.freeze([ "DASHBOARD_ASSISTANT_ENCRYPTION_SECRET", "SESSION_SECRET", "SECRET_KEY", ]); // enc-v2 values are minted ONLY under the dedicated secret. SESSION_SECRET // stays in the candidate list purely for decryption of legacy values that // older versions minted under its deprecated fallback (the startup migration // re-wraps those under the dedicated secret, but until that succeeds they // must stay readable) — new values are never keyed with it, and decryption // never consults SECRET_KEY. const ASSISTANT_PROVIDER_SECRET_V2_ENV_KEYS = Object.freeze([ "DASHBOARD_ASSISTANT_ENCRYPTION_SECRET", "SESSION_SECRET", ]); const ASSISTANT_PROVIDER_SECRET_V2_SALT_BYTES = 16; // 128 * r * (N + p + 2) exceeds the 32 MiB scrypt default, hence maxmem. const ASSISTANT_PROVIDER_SECRET_V2_SCRYPT_PARAMS = Object.freeze({ N: 2 ** 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024, }); const ASSISTANT_SERVER_PAGE_SECTION_LABELS = Object.freeze({ console: "console", info: "info", files: "files", activity: "activity", backups: "backups", scheduler: "scheduler", store: "store", resource_stats: "resource stats", reinstall: "reinstall", ai_help: "AI help", }); const ASSISTANT_SETTINGS_PANEL_LABELS = Object.freeze({ preferences: "Preferences", customization: "Customization", account: "Account", security: "Security", databases: "Databases", nodes: "Nodes", templates: "Templates", servers: "Servers", webhooks: "Webhooks", panelinfo: "Panel Info", }); const ASSISTANT_SETTINGS_ACTION_LABELS = Object.freeze({ create_user: "Create User", branding: "Branding", login_background: "Login Background", alert: "Alerts", database_setup: "Database Setup", pgadmin_setup: "pgAdmin Setup", mongodb_setup: "MongoDB Setup", captcha: "Captcha", maintenance: "Maintenance", create_node: "Create Node", create_template: "Create Template", add_webhook: "Add Webhook", }); const accessibleServersForAssistantCache = new Map(); const ASSISTANT_PROVIDER_HTTPS_AGENTS = Object.freeze({ groq: new https.Agent({ keepAlive: true, keepAliveMsecs: 10_000, maxSockets: 24, maxFreeSockets: 12, timeout: 90_000, }), google: new https.Agent({ keepAlive: true, keepAliveMsecs: 10_000, maxSockets: 24, maxFreeSockets: 12, timeout: 90_000, }), }); // Fixed-length placeholder for a stored key: the mask must not disclose the // real secret's size, so every non-empty key renders identically. Constant // value keeps it deterministic across requests; empty still means "no key set". const STORED_KEY_MASK = "\u2022".repeat(12); function buildStoredKeyFieldValue(value) { const clean = String(value || "").trim(); if (!clean) return ""; return STORED_KEY_MASK; } function normalizeMessageContent(content) { if (Array.isArray(content)) { return content .map((part) => { if (typeof part === "string") return part; if (part && typeof part.text === "string") return part.text; if (part && part.type === "text" && typeof part.text === "string") return part.text; return ""; }) .join("") .trim(); } return String(content || "").trim(); } function stripAssistantLookupDiacritics(value) { return String(value || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, ""); } function normalizeAssistantLookupText(value) { return stripAssistantLookupDiacritics(value) .toLowerCase() .replace(/[`"'“”‘’()[\]{}<>]/g, " ") .replace(/[_./-]+/g, " ") .replace(/[^a-z0-9 ]+/g, " ") .replace(/\s+/g, " ") .trim(); } function compactAssistantLookupText(value) { return normalizeAssistantLookupText(value).replace(/\s+/g, ""); } function getAssistantServerMentionAliases(entry) { const aliases = new Set(); for (const value of [entry?.name, entry?.displayName, entry?.id, entry?.bot, entry?.legacyId]) { const clean = String(value || "").trim(); if (!clean) continue; aliases.add(clean); const spaced = clean.replace(/[_./-]+/g, " ").replace(/\s+/g, " ").trim(); if (spaced) aliases.add(spaced); } return Array.from(aliases); } function inferAssistantServerMention(message, accessibleServers) { const raw = String(message || "").trim(); if (!raw) return null; const normalizedMessage = normalizeAssistantLookupText(raw); const compactMessage = compactAssistantLookupText(raw); if (!normalizedMessage && !compactMessage) return null; const wrappedMentions = Array.from(raw.matchAll(/["'`“”(\[]([^"'`“”()[\]]{1,120})["'`”)\]]/g)) .map((match) => String(match?.[1] || "").trim()) .filter(Boolean); const normalizedWrapped = wrappedMentions.map((value) => normalizeAssistantLookupText(value)).filter(Boolean); const compactWrapped = wrappedMentions.map((value) => compactAssistantLookupText(value)).filter(Boolean); const scored = (Array.isArray(accessibleServers) ? accessibleServers : []) .filter((entry) => entry?.name) .map((entry) => { let best = 0; for (const alias of getAssistantServerMentionAliases(entry)) { const normalizedAlias = normalizeAssistantLookupText(alias); const compactAlias = compactAssistantLookupText(alias); if (!normalizedAlias && !compactAlias) continue; if (normalizedAlias && normalizedWrapped.includes(normalizedAlias)) { best = Math.max(best, 1600 + normalizedAlias.length); } if (compactAlias && compactWrapped.includes(compactAlias)) { best = Math.max(best, 1550 + compactAlias.length); } if (normalizedAlias && normalizedMessage && ` ${normalizedMessage} `.includes(` ${normalizedAlias} `)) { best = Math.max(best, 1200 + normalizedAlias.length); } if (compactAlias && compactAlias.length >= 4 && compactMessage.includes(compactAlias)) { best = Math.max(best, 900 + compactAlias.length); } const aliasTokens = normalizedAlias.split(" ").filter(Boolean); if (aliasTokens.length >= 2) { const overlap = aliasTokens.filter((token) => ` ${normalizedMessage} `.includes(` ${token} `)).length; if (overlap === aliasTokens.length) { best = Math.max(best, 650 + aliasTokens.length * 40); } else if (overlap > 0) { best = Math.max(best, 240 + overlap * 35); } } else if (aliasTokens.length === 1 && aliasTokens[0].length >= 4 && ` ${normalizedMessage} `.includes(` ${aliasTokens[0]} `)) { best = Math.max(best, 520 + aliasTokens[0].length); } } return { entry, score: best }; }) .filter((item) => item.score > 0) .sort((left, right) => right.score - left.score); if (!scored.length) return null; const [best, second] = scored; if (second && best.score < second.score + 140) { return null; } if (best.score < 520) { return null; } return { name: best.entry.name, displayName: best.entry.displayName || best.entry.name, score: best.score, }; } function inferAssistantServerMentionFromHistory(messages, accessibleServers, limit = 12) { const recent = (Array.isArray(messages) ? messages : []) .filter((entry) => entry && (entry.role === "user" || entry.role === "assistant")) .slice(-limit); for (let index = recent.length - 1; index >= 0; index -= 1) { const content = normalizeMessageContent(recent[index]?.content); if (!content) continue; const mention = inferAssistantServerMention(content, accessibleServers); if (mention?.name) return mention; } return null; } function sanitizeToken(rawToken) { return String(rawToken || "").replace(/\0/g, "").replace(/[\r\n]+/g, "").trim(); } // Envelope version of a stored encrypted provider value ("enc-v1"/"enc-v2"): // the prefix before the first ":". Empty input means no stored envelope and // yields "" — the legacy PLAINTEXT env fallback (GROQ_API_KEY etc.) therefore // deliberately maps to "" too: plaintext at rest is a pre-existing at-rest // hygiene issue (saveProviderToken already re-wraps and purges it), not a // weakening of the key DERIVATION chain, so the fail-closed legacy guard is // scoped to stored enc-v1 envelopes only. function assistantProviderEnvelopeVersion(value) { const stored = String(value || ""); return stored ? stored.split(":")[0] : ""; } // POST /token key validation. The panel only ever talks to the fixed Groq and // Google AI Studio endpoints, whose real keys are opaque single-line // printable-ASCII strings (Groq "gsk_…" keys are 56 chars, Google "AIza…" // keys are 39), so these bounds are generous and no legitimate key can fail. // Every rejection reuses one generic, secret-free message so format probes // learn nothing granular; "valid" keeps inferStatusCode mapping it to 400. const ASSISTANT_PROVIDER_TOKEN_MIN_LENGTH = 20; const ASSISTANT_PROVIDER_TOKEN_MAX_LENGTH = 256; const ASSISTANT_PROVIDER_TOKEN_PLACEHOLDERS = new Set(["your-api-key", "undefined", "null"]); function validateProviderApiToken(rawToken, providerLabel) { const token = typeof rawToken === "string" ? rawToken.trim() : ""; // \x21-\x7e is printable ASCII minus space: real keys never contain // whitespace, control bytes or non-ASCII characters. const isWellFormed = token.length >= ASSISTANT_PROVIDER_TOKEN_MIN_LENGTH && token.length <= ASSISTANT_PROVIDER_TOKEN_MAX_LENGTH && !/[^\x21-\x7e]/.test(token) && !ASSISTANT_PROVIDER_TOKEN_PLACEHOLDERS.has(token.toLowerCase()); if (!isWellFormed) { throw new Error(`Please enter a valid ${providerLabel} API key.`); } return token; } function sanitizeTranscriptionLanguage(value) { // Client-controlled value: non-string inputs are rejected rather than coerced — coercion can throw on null-prototype objects and smuggle unexpected characters. const primary = typeof value === "string" ? value.trim().toLowerCase().split(/[-_]/)[0] : ""; return /^[a-z]{2,3}$/.test(primary) ? primary : ""; } function sanitizeTranscriptionPrompt(value) { const clean = String(value || "").replace(/\s+/g, " ").trim(); return clean.slice(0, 500); } function sanitizeProvider(value) { const provider = String(value || "").trim().toLowerCase(); return SUPPORTED_PROVIDERS.has(provider) ? provider : ""; } function getProviderLabel(provider) { return PROVIDER_LABELS[sanitizeProvider(provider)] || "AI provider"; } function getAssistantProviderSecretConfig(provider) { return ASSISTANT_PROVIDER_SECRET_ENV_KEYS[sanitizeProvider(provider)] || null; } // Flipped to true ONLY when the startup migration confirms .env holds zero // enc-v1 provider values (nothing found, every value re-wrapped to enc-v2 // and written successfully, or every persistently-undecryptable value // quarantined into its ORPHANED_V1 recovery slot and the write verified). // While false, SECRET_KEY stays a decrypt-only enc-v1 candidate; once true // it is dropped for the rest of the process. The flag is one-way per // process: while retirement is unconfirmed, the migration retry scheduler // (see runAssistantProviderSecretMigrationOnce) keeps re-running the // migration in this process with backoff instead of waiting for the next // boot, and every fresh boot starts a migration too. let assistantProviderSecretV1Retired = false; // Quarantine gate for persistently-undecryptable enc-v1 values: the number // of CONSECUTIVE migration runs (within one process) in which the SAME live // value failed to decrypt under the full legacy chain before the migration // treats the loss as proven and moves the value to its ORPHANED_V1 recovery // slot. The threshold exists because a transient condition (a .env read // racing a save, a secret provisioned a tick late) must never be misread as // permanent loss and strip a live key out of its slot; 4 means the first // attempt plus 3 retries — with the scheduler's 30s → 2min → 10min backoff // that is ~12.5 minutes of proven, unhealed failure inside a single boot, // far beyond any transient hiccup the retry scheduler exists to absorb. const ASSISTANT_PROVIDER_SECRET_QUARANTINE_THRESHOLD = 4; // Per-LIVE-env-key persistence tracking for undecryptable enc-v1 values: // { value, streak } — the exact ciphertext that failed and how many // consecutive runs it has failed in. Process-lifetime only (every boot // re-proves persistence from scratch) and reset whenever the live value // changes: a different ciphertext gets the full benefit of the doubt. The // entry is cleared when the value re-wraps successfully, is quarantined, or // disappears from its slot. Keyed by the live key (not the provider id) so // the tracking follows the slot, not the provider. const assistantProviderSecretUndecryptableStreaks = new Map(); // Curated, secret-free vocabulary for why a migration run ended with // retirement unconfirmed. Recorded in // assistantProviderSecretMigrationState.lastFailureReason and surfaced to // admins via getAssistantProviderSecretMigrationState(), so values must never // embed key material, .env contents or raw error text — only a fixed term an // operator can act on. "" means the last run confirmed retirement (or nothing // has failed yet). const ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS = Object.freeze({ DEPS_UNAVAILABLE: "deps-unavailable", ENV_READ_FAILED: "env-read-failed", ENV_WRITE_FAILED: "env-write-failed", VERIFIED_WRITE_REFUSED: "verified-write-refused", UNDECRYPTABLE_VALUE: "undecryptable-value", MISSING_DEDICATED_SECRET: "missing-dedicated-secret", }); // Health bookkeeping for the enc-v1 migration within this process, written by // migrateAssistantProviderSecretsV1ToV2 on every run (scheduler-driven or // direct) and by the retry scheduler. Primitive fields only: this state is // exposed through getAssistantProviderSecretMigrationState() for the // admin-facing status surface, so it must stay trivially serializable and // secret-free by construction. const assistantProviderSecretMigrationState = { attempted: false, // any migrate run has happened in this process attempts: 0, // total runs, including direct (test/tooling) calls lastAttemptAtMs: 0, // epoch ms of the last run's start lastFailureReason: "", // curated reason from the table above; "" = last run retired nextRetryAtMs: 0, // epoch ms the retry scheduler next runs the migration, 0 = none pending }; // Cross-agent contract: the admin status surface and the fail-closed chat // guard consume THIS exact shape — do not rename or add fields lightly. // Returns a fresh plain object of primitives (no references into module // state, no secret material), so callers can hold or serialize it freely. function getAssistantProviderSecretMigrationState() { return { attempted: assistantProviderSecretMigrationState.attempted, retired: assistantProviderSecretV1Retired, attempts: assistantProviderSecretMigrationState.attempts, lastAttemptAtMs: assistantProviderSecretMigrationState.lastAttemptAtMs, nextRetryAtMs: assistantProviderSecretMigrationState.nextRetryAtMs, lastFailureReason: assistantProviderSecretMigrationState.lastFailureReason, }; } const assistantProviderCipherKeyCache = new Map(); const ASSISTANT_PROVIDER_CIPHER_KEY_CACHE_LIMIT = 16; function getAssistantProviderSecretCandidates(envKeys) { const seen = new Set(); const candidates = []; for (const envKey of envKeys) { const candidate = sanitizeToken(process.env[envKey] || ""); if (!candidate || seen.has(candidate)) continue; seen.add(candidate); candidates.push(candidate); } return candidates; } function getAssistantProviderSecretForEncryption() { const dedicated = sanitizeToken(process.env.DASHBOARD_ASSISTANT_ENCRYPTION_SECRET || ""); if (dedicated) return dedicated; // Fail closed: new enc-v2 values are minted ONLY under the dedicated // secret. The deprecated SESSION_SECRET mint fallback is gone — that // secret is shared with session signing (a weak or leaked session secret // would expose every provider key, and rotating it would orphan them), so // it must never key new ciphertexts. index.js auto-provisions the // dedicated secret into .env at startup, so reaching this throw means // provisioning failed (e.g. a read-only .env) and the operator must set // DASHBOARD_ASSISTANT_ENCRYPTION_SECRET manually. Decryption is NOT // affected: values minted under the old fallback stay decryptable via // ASSISTANT_PROVIDER_SECRET_V2_ENV_KEYS, and the startup migration // re-wraps them under the dedicated secret. // The message prefix ("encryption secret is unavailable") is load-bearing: // routes/dashboard-assistant.js classifies it as a curated 503 instead of // a generic 500. throw new Error( "Assistant encryption secret is unavailable. Set DASHBOARD_ASSISTANT_ENCRYPTION_SECRET in .env to a dedicated random value to store provider API keys (it is normally auto-provisioned into .env at startup)." ); } function deriveAssistantProviderCipherKeyV1(secretMaterial) { // Legacy enc-v1 KDF: an unsalted, unstretched SHA-256. Kept verbatim so // existing .env ciphertexts stay decryptable; new values use enc-v2. return crypto .createHash("sha256") .update(ASSISTANT_PROVIDER_SECRET_CONTEXT) .update("\0") .update(secretMaterial) .digest(); } function deriveAssistantProviderCipherKeyV2(secretMaterial, salt) { // enc-v2 KDF: memory-hard scrypt with a per-value random salt. The context // string is folded into the salt input (context\0salt) so the derivation // stays domain-separated and deterministic for a given (secret, salt). const saltInput = Buffer.concat([ Buffer.from(ASSISTANT_PROVIDER_SECRET_CONTEXT), Buffer.from([0]), salt, ]); return crypto.scryptSync( secretMaterial, saltInput, 32, ASSISTANT_PROVIDER_SECRET_V2_SCRYPT_PARAMS ); } function getCachedAssistantProviderCipherKey(version, salt, secretMaterial, deriveKey) { // Decrypts run on every chat request, so derived keys are cached by // (version, salt, secret) and the cache is bounded: every save mints a // fresh salt and leaves the previous entry dead weight. const cacheKey = `${version}\0${salt.toString("base64")}\0${secretMaterial}`; const cached = assistantProviderCipherKeyCache.get(cacheKey); if (cached) return cached; const key = deriveKey(); if (assistantProviderCipherKeyCache.size >= ASSISTANT_PROVIDER_CIPHER_KEY_CACHE_LIMIT) { assistantProviderCipherKeyCache.clear(); } assistantProviderCipherKeyCache.set(cacheKey, key); return key; } function decryptAssistantProviderTokenParts(key, ivBase64, authTagBase64, ciphertextBase64) { // authTagLength: 16 pins GCM to full-length tags: setAuthTag rejects // truncated tags instead of decrypting under a partial MAC. const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(ivBase64, "base64"), { authTagLength: 16, }); decipher.setAuthTag(Buffer.from(authTagBase64, "base64")); return Buffer.concat([ decipher.update(Buffer.from(ciphertextBase64, "base64")), decipher.final(), ]).toString("utf8"); } function decryptProviderTokenFields(version, salt, ivBase64, authTagBase64, ciphertextBase64, candidates, deriveKey) { if (!candidates.length) { throw new Error("Assistant encryption secret is unavailable."); } let lastError = null; for (const secretMaterial of candidates) { try { const key = getCachedAssistantProviderCipherKey(version, salt, secretMaterial, () => deriveKey(secretMaterial) ); const plaintext = decryptAssistantProviderTokenParts(key, ivBase64, authTagBase64, ciphertextBase64); return sanitizeToken(plaintext); } catch (error) { lastError = error; } } throw lastError; } function encryptAssistantProviderToken(rawToken) { const token = sanitizeToken(rawToken); if (!token) return ""; // Provider API keys must stay reversible so the assistant can call Groq/Google later. // Always emitting enc-v2 lazily re-wraps legacy enc-v1 values on the next // save; read paths never rewrite .env. const secretMaterial = getAssistantProviderSecretForEncryption(); const salt = crypto.randomBytes(ASSISTANT_PROVIDER_SECRET_V2_SALT_BYTES); const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv( "aes-256-gcm", getCachedAssistantProviderCipherKey( ASSISTANT_PROVIDER_SECRET_VERSION_V2, salt, secretMaterial, () => deriveAssistantProviderCipherKeyV2(secretMaterial, salt) ), iv, { authTagLength: 16 } ); const ciphertext = Buffer.concat([cipher.update(token, "utf8"), cipher.final()]); const authTag = cipher.getAuthTag(); return [ ASSISTANT_PROVIDER_SECRET_VERSION_V2, salt.toString("base64"), iv.toString("base64"), authTag.toString("base64"), ciphertext.toString("base64"), ].join(":"); } function decryptAssistantProviderTokenV1(fields) { const [ivBase64, authTagBase64, ciphertextBase64] = fields; if (!ivBase64 || !authTagBase64 || !ciphertextBase64) { throw new Error("Invalid assistant provider token format."); } // Legacy enc-v1 payloads were keyed by whichever secret the old chain found // first; candidates are tried in that original order and the first whose // GCM tag authenticates wins, so old ciphertexts keep working both before // and after an operator adds DASHBOARD_ASSISTANT_ENCRYPTION_SECRET. While // enc-v1 may still exist (retirement not yet confirmed), the chain is the // full legacy list including SECRET_KEY; once the startup migration // confirms .env has no enc-v1 values, SECRET_KEY — the reCAPTCHA site // secret, wired in here only as a last resort — is dropped by falling back // to the V2 candidate list for the rest of the process. return decryptProviderTokenFields( ASSISTANT_PROVIDER_SECRET_VERSION, Buffer.alloc(0), ivBase64, authTagBase64, ciphertextBase64, getAssistantProviderSecretCandidates( assistantProviderSecretV1Retired ? ASSISTANT_PROVIDER_SECRET_V2_ENV_KEYS : ASSISTANT_PROVIDER_SECRET_LEGACY_ENV_KEYS ), (secretMaterial) => deriveAssistantProviderCipherKeyV1(secretMaterial) ); } function decryptAssistantProviderTokenV2(fields) { const [saltBase64, ivBase64, authTagBase64, ciphertextBase64] = fields; if (!saltBase64 || !ivBase64 || !authTagBase64 || !ciphertextBase64) { throw new Error("Invalid assistant provider token format."); } // Same rotation logic as enc-v1, but SECRET_KEY is never a candidate // because enc-v2 values are never minted under the reCAPTCHA secret. The // SESSION_SECRET candidate is legacy-decrypt-only: it still resolves values // that older versions minted under the deprecated fallback, but nothing // mints under it anymore (getAssistantProviderSecretForEncryption fails // closed without the dedicated secret). return decryptProviderTokenFields( ASSISTANT_PROVIDER_SECRET_VERSION_V2, Buffer.from(saltBase64, "base64"), ivBase64, authTagBase64, ciphertextBase64, getAssistantProviderSecretCandidates(ASSISTANT_PROVIDER_SECRET_V2_ENV_KEYS), (secretMaterial) => deriveAssistantProviderCipherKeyV2(secretMaterial, Buffer.from(saltBase64, "base64")) ); } function decryptAssistantProviderToken(payload) { const value = sanitizeToken(payload); if (!value) return ""; const parts = value.split(":"); if (parts[0] === ASSISTANT_PROVIDER_SECRET_VERSION_V2) { return decryptAssistantProviderTokenV2(parts.slice(1)); } if (parts[0] === ASSISTANT_PROVIDER_SECRET_VERSION) { return decryptAssistantProviderTokenV1(parts.slice(1)); } throw new Error("Invalid assistant provider token format."); } // Tries an enc-v2 envelope against an EXPLICIT list of secrets instead of the // ordered ASSISTANT_PROVIDER_SECRET_V2_ENV_KEYS chain. Only the startup // migration needs this: it must distinguish "already keyed under the // dedicated secret" (leave the value untouched) from "still keyed under the // deprecated SESSION_SECRET mint fallback" (re-wrap), which the shared chain // — where the first authenticating candidate wins silently — cannot express. function decryptAssistantProviderTokenV2With(storedValue, secretMaterials) { const [saltBase64, ivBase64, authTagBase64, ciphertextBase64] = storedValue.split(":").slice(1); if (!saltBase64 || !ivBase64 || !authTagBase64 || !ciphertextBase64) { throw new Error("Invalid assistant provider token format."); } const salt = Buffer.from(saltBase64, "base64"); return decryptProviderTokenFields( ASSISTANT_PROVIDER_SECRET_VERSION_V2, salt, ivBase64, authTagBase64, ciphertextBase64, secretMaterials, (secretMaterial) => deriveAssistantProviderCipherKeyV2(secretMaterial, salt) ); } // Startup migration (self-healing: while retirement stays unconfirmed, the // retry scheduler below re-runs it in this process with backoff, so a // transient failure does not wait for the next boot): re-encrypts provider // API keys found in .env so // every stored value ends up as enc-v2 under the dedicated // DASHBOARD_ASSISTANT_ENCRYPTION_SECRET, and, when no enc-v1 value remains, // flips assistantProviderSecretV1Retired so SECRET_KEY is dropped from the // enc-v1 decryption chain for the rest of the process. Two value classes are // re-wrapped: // - enc-v1 values (legacy unsalted-SHA-256 KDF), decrypted via the full // legacy chain — SECRET_KEY included, this migration is the only caller // that may still consult it; // - enc-v2 values that do NOT decrypt under the dedicated secret but DO // under SESSION_SECRET: output of the deprecated mint fallback that // older versions used when the dedicated secret was unset. Values // already keyed under the dedicated secret stay byte-for-byte untouched // (no salt churn, no needless .env mtime bump). // A THIRD class is quarantined rather than re-wrapped: an enc-v1 value that // fails decryption under the full legacy chain while the dedicated secret is // present, and whose failure is proven persistent — the SAME value failing // ASSISTANT_PROVIDER_SECRET_QUARANTINE_THRESHOLD consecutive runs in this // process — is MOVED out of its live slot into the provider's dedicated // *_ORPHANED_V1 recovery slot (empty-slot-only, verified-write guarded) in // the run's single batch. Quarantine is never destruction: the ciphertext // survives verbatim for manual recovery, recovery artifacts are never // overwritten, and no runtime path reads them. What quarantine buys is the // elimination of the weak state from the LIVE config: the live slot becomes // enc-v1-free, so SECRET_KEY retirement can confirm and the captcha secret // leaves the decryption chain (an undecryptable value is functionally dead — // the chat path already reports "not configured" for it). A value whose // failure is NOT yet persistent (or whose quarantine is blocked by an // occupied recovery slot, or a missing dedicated secret) is left untouched, // exactly as before. // Scheduled via setImmediate from createDashboardAssistantService (never // blocks boot; by then index.js has auto-provisioned the dedicated secret) // and re-run by the retry scheduler while unretired; read paths never // rewrite .env — this migration is the one exception, and only it may // consult the full legacy chain (including SECRET_KEY) to re-wrap an old // value. // // Ordering per run: read .env → classify/decrypt each value → re-encrypt as // enc-v2 under the dedicated secret (or stage a quarantine move for a // persistently-undecryptable enc-v1 value) → round-trip verify → single // batch write (only changed entries: re-wraps AND quarantine moves together) // → mirror into process.env → flip the retirement flag. // // Returns { retired, migrated } for tests/callers and NEVER throws: a missing // or failing dep, a not-yet-persistent undecryptable value, or a failed write // skips/aborts the run with the old .env value(s) and the full legacy chain // left untouched. `migrated` counts re-wraps only — quarantined values are // handled separately and block nothing once their verified write lands. // Every run also updates assistantProviderSecretMigrationState (attempted / // attempts / timing / curated secret-free failure reason) so the retry // scheduler and the admin status surface can see WHY a run did not retire. // An empty-looking .env counts as unconfirmed too: readEnvFile returns {} both // for an empty file and on a read error it swallows, so retirement is only // confirmed when the read env actually has entries — an empty read keeps the // full legacy chain until a scheduled retry or a later boot reads real // content and re-confirms. function migrateAssistantProviderSecretsV1ToV2(deps) { const outcome = { retired: false, migrated: 0 }; // Every run — scheduler-driven or direct — updates the shared migration // state first, so the getter always reflects reality even when the run // bails at the very first guard. All values are secret-free primitives. assistantProviderSecretMigrationState.attempted = true; assistantProviderSecretMigrationState.attempts += 1; assistantProviderSecretMigrationState.lastAttemptAtMs = Date.now(); if (!deps || typeof deps !== "object") { assistantProviderSecretMigrationState.lastFailureReason = ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS.DEPS_UNAVAILABLE; return outcome; } let env = null; if (typeof deps.readEnvFile !== "function") { assistantProviderSecretMigrationState.lastFailureReason = ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS.DEPS_UNAVAILABLE; console.warn( "[dashboard-assistant] enc-v1 migration skipped: readEnvFile dependency is unavailable; SECRET_KEY stays an enc-v1 decryption candidate." ); return outcome; } try { env = deps.readEnvFile(); } catch { assistantProviderSecretMigrationState.lastFailureReason = ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS.ENV_READ_FAILED; console.warn( "[dashboard-assistant] enc-v1 migration skipped: .env could not be read; SECRET_KEY stays an enc-v1 decryption candidate." ); return outcome; } if (!env || typeof env !== "object") { assistantProviderSecretMigrationState.lastFailureReason = ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS.ENV_READ_FAILED; console.warn( "[dashboard-assistant] enc-v1 migration skipped: .env could not be read; SECRET_KEY stays an enc-v1 decryption candidate." ); return outcome; } // Re-wrapping always targets the dedicated secret: // encryptAssistantProviderToken mints only under it and fails closed when // it is unset (the startup provisioning in index.js normally guarantees // it). SESSION_SECRET matters here only as the DECRYPTION key for values // the deprecated mint fallback produced. const dedicatedSecret = sanitizeToken(process.env.DASHBOARD_ASSISTANT_ENCRYPTION_SECRET || ""); const sessionSecret = sanitizeToken(process.env.SESSION_SECRET || ""); const updates = {}; // The exact pre-read values each replacement was derived from, keyed by the // same env key: handed to deps.writeEnvFileBatchVerified so the host can // re-check them under the .env lock before applying the batch (lost-update // guard — see the write site below). Quarantine moves use the same guard // twice over: expectedOriginals[liveKey] pins the value being moved, and // expectedOriginals[orphanKey] = "" asserts the recovery slot is STILL // empty under the lock (two workers quarantining different values race — // the loser's whole batch is refused). const expectedOriginals = {}; let migrated = 0; let failed = 0; // Values moved to their ORPHANED_V1 recovery slot this run. Quarantined // values count as HANDLED: they neither increment `migrated` (which counts // re-wraps only — the public outcome shape stays { retired, migrated }) nor // `failed` (only unhandled values block retirement), so their details are // tracked here for the post-write mirror, streak clearing and logging. let quarantined = 0; const quarantinedMoves = []; // Which curated failure reason the enc-v1 re-wrap failures map to. Both // stay false unless at least one enc-v1 value failed to re-wrap; when both // could apply, missing-dedicated-secret wins because it is the actionable // one (provisioning the secret lets the next retry migrate the value, // whereas an undecryptable value is unfixable by configuration). let sawMissingDedicatedSecret = false; let sawUndecryptableV1 = false; for (const providerId of Object.keys(PROVIDER_LABELS)) { const secretConfig = getAssistantProviderSecretConfig(providerId); if (!secretConfig) continue; const storedValue = sanitizeToken(env[secretConfig.encrypted] || ""); // The live slot no longer holds what the streak map tracks (the value was // re-wrapped, re-saved, quarantined, or disappeared): a different or gone // ciphertext gets the full benefit of the doubt — its failure history is // discarded so persistence must be re-proven from scratch. const trackedStreak = assistantProviderSecretUndecryptableStreaks.get(secretConfig.encrypted); if (trackedStreak && trackedStreak.value !== storedValue) { assistantProviderSecretUndecryptableStreaks.delete(secretConfig.encrypted); } if (!storedValue) continue; const storedVersion = storedValue.split(":")[0]; let replacement = ""; // Flipped inside the try once a usable plaintext is in hand: any failure // after that point is on the mint/round-trip side, never the decryption // side, and must not accrue quarantine credit (the catch below reads it). let decryptedOk = false; if (storedVersion === ASSISTANT_PROVIDER_SECRET_VERSION) { try { // The only remaining caller of the full legacy chain (SECRET_KEY // included), so a value keyed under it can still be re-wrapped. const plaintext = decryptAssistantProviderToken(storedValue); if (!plaintext) throw new Error("decrypted to an empty token"); decryptedOk = true; const reEncrypted = encryptAssistantProviderToken(plaintext); // Round-trip gate: overwrite .env only when the fresh enc-v2 envelope // decrypts back to exactly the same token under the V2 chain. if (decryptAssistantProviderToken(reEncrypted) !== plaintext) { throw new Error("enc-v2 round-trip verification failed"); } replacement = reEncrypted; } catch { // The value stays in its live slot for now; retirement must not be // confirmed while any enc-v1 value could not be handled. // Curated failure reason for the migration state: without a dedicated // secret the re-wrap can ONLY fail at the encrypt step (the value // itself may well have decrypted fine via the legacy chain), so // "missing-dedicated-secret" is the accurate, actionable diagnosis. // With a dedicated secret present, a failure is either genuine // undecryptability (quarantine-eligible, tracked below) or a // mint/round-trip fault on a value we JUST decrypted — the latter is // provably not an orphan and never moves (see decryptedOk below). if (!dedicatedSecret) { failed += 1; sawMissingDedicatedSecret = true; } else if (decryptedOk) { // Mint/round-trip fault on a value whose plaintext WAS just // recovered: it stays in its live slot, loud (failed += 1 blocks // retirement), until the crypto layer works again — it never // accrues streak credit and is never quarantined. failed += 1; } else { sawUndecryptableV1 = true; // Persistence tracking: the SAME value failing again extends its // streak; anything else restarted above at 1. const priorStreak = assistantProviderSecretUndecryptableStreaks.get(secretConfig.encrypted); const streak = (priorStreak && priorStreak.value === storedValue ? priorStreak.streak : 0) + 1; assistantProviderSecretUndecryptableStreaks.set(secretConfig.encrypted, { value: storedValue, streak }); // Quarantine preconditions — ALL must hold, otherwise this run // behaves exactly as before (value untouched, failed += 1, // retirement blocked, loud retries): // (a) stored version is exactly "enc-v1" — guaranteed: this is // the enc-v1 branch's catch; // (b) decryption under the full legacy chain failed — this catch; // (c) the dedicated secret is PRESENT — the anti-mis-quarantine // invariant: with provisioning broken the value might decrypt // once the secret lands, so it is never quarantined then (the // missing-dedicated-secret failure path above keeps its // existing behavior and loud retry); // (d) the streak reached the persistence threshold — the failure // is proven, not transient; // (e) the provider's ORPHANED_V1 recovery slot is currently EMPTY // — ABSOLUTE invariant: an existing recovery artifact is // never overwritten. If occupied, the live value stays put, // keeps counting as failed (retirement stays blocked) and the // loud retry loop continues — the corner-of-corner of an // occupied slot plus a new undecryptable value stays exactly // as today, deliberately, because destroying or overwriting // the artifact would be data loss. const orphanKey = ASSISTANT_PROVIDER_SECRET_ORPHANED_V1_ENV_KEYS[providerId] || ""; // Occupancy comes from the fresh .env snapshot ONLY: when the // snapshot has entries it is the complete file, so an absent orphan // key means the line is really gone — a stale process.env mirror // left by this process's own earlier quarantine must not keep the // slot pinned occupied after the operator follows the Discard // guidance mid-process. On an empty/untrusted snapshot (a swallowed // read error), treat the slot as occupied: never act on a read we // cannot see. const orphanOccupied = Object.keys(env).length > 0 ? !!sanitizeToken(env[orphanKey] || "") : true; if ( streak >= ASSISTANT_PROVIDER_SECRET_QUARANTINE_THRESHOLD && orphanKey && !orphanOccupied ) { // Quarantine, not destruction: move the EXACT stored string out // of the live slot into the empty recovery slot, riding this // run's single batch (multiple providers may quarantine in one // write, exactly like re-wraps). The live key's null entry // deletes its .env line; the verified-writer originals pin the // move from both ends (see expectedOriginals above). updates[secretConfig.encrypted] = null; updates[orphanKey] = storedValue; expectedOriginals[secretConfig.encrypted] = storedValue; expectedOriginals[orphanKey] = ""; quarantined += 1; quarantinedMoves.push({ providerLabel: PROVIDER_LABELS[providerId] || "AI provider", liveKey: secretConfig.encrypted, orphanKey, storedValue, streak, }); } else { failed += 1; } } } } else if (storedVersion === ASSISTANT_PROVIDER_SECRET_VERSION_V2 && dedicatedSecret) { // enc-v2: re-wrap only legacy-minted values — ones the dedicated // secret CANNOT open but SESSION_SECRET can. An undecryptable value is // left untouched (data loss is worse than a stale envelope) and, being // enc-v2, does not block SECRET_KEY retirement. let plaintext = ""; try { decryptAssistantProviderTokenV2With(storedValue, [dedicatedSecret]); } catch { try { plaintext = sessionSecret ? decryptAssistantProviderTokenV2With(storedValue, [sessionSecret]) : ""; } catch { plaintext = ""; // keyed under neither known secret: leave untouched } } if (plaintext) { try { const reEncrypted = encryptAssistantProviderToken(plaintext); // Same round-trip gate as the enc-v1 path above. if (decryptAssistantProviderToken(reEncrypted) !== plaintext) { throw new Error("enc-v2 round-trip verification failed"); } replacement = reEncrypted; } catch { replacement = ""; } } } else { // Unknown envelope version, or enc-v2 with no dedicated secret to // re-wrap under: leave untouched. continue; } if (replacement) { updates[secretConfig.encrypted] = replacement; // Record the exact pre-read value this replacement was derived from: // the verified write path re-checks it under the .env lock, so a // concurrent save that replaced this line in the meantime is never // silently reverted by this stale re-encryption (lost update). expectedOriginals[secretConfig.encrypted] = storedValue; migrated += 1; // A successful re-wrap resolves any failure history for this slot. assistantProviderSecretUndecryptableStreaks.delete(secretConfig.encrypted); } } if (quarantined === 0 && !migrated && !failed && Object.keys(env).length > 0) { // Nothing in .env is enc-v1: confirm retirement without touching .env — // its mtime is the cross-worker cache-invalidation signal and must not // change needlessly. // // The flip additionally requires the read env to be non-empty: readEnvFile // returns {} both for a genuinely empty file and when the read fails (it // swallows errors), so {} alone is no proof that no enc-v1 value exists. // An empty-looking env keeps the full legacy chain — SECRET_KEY stays a // decrypt-only candidate, the conservative choice — and falls through to // the no-migration return below, recorded as env-read-failed in the // migration state but deliberately without extra log noise; a scheduled // in-process retry, or the next boot reading real .env content, // re-confirms retirement. assistantProviderSecretV1Retired = true; outcome.retired = true; // Full success: clear the failure history and any pending-retry marker // (the scheduler also stops scheduling once retired). assistantProviderSecretMigrationState.lastFailureReason = ""; assistantProviderSecretMigrationState.nextRetryAtMs = 0; return outcome; } if (quarantined === 0 && !migrated) { // Every enc-v1 value failed to re-wrap (e.g. its secret is lost, or its // quarantine is blocked by an occupied ORPHANED_V1 slot): leave .env // untouched and keep the full legacy chain, flag included. The retry // scheduler treats unretired outcomes as retryable, so record WHY: // failed > 0 means re-wrap failures; failed === 0 here can only be the // empty-looking-.env case above (Object.keys(env).length === 0), which is // an UNCONFIRMED state rather than a success — treated like an // unreadable .env for state purposes, still without extra log noise. assistantProviderSecretMigrationState.lastFailureReason = failed > 0 ? (sawMissingDedicatedSecret ? ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS.MISSING_DEDICATED_SECRET : ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS.UNDECRYPTABLE_VALUE) : ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS.ENV_READ_FAILED; return outcome; } if (typeof deps.writeEnvFileBatch !== "function") { assistantProviderSecretMigrationState.lastFailureReason = ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS.ENV_WRITE_FAILED; console.warn( "[dashboard-assistant] enc-v1 migration skipped: writeEnvFileBatch dependency is unavailable; SECRET_KEY stays an enc-v1 decryption candidate." ); return outcome; } // Verify-under-lock write: this run read .env at t0 and spent ~100-200 ms // decrypting/re-encrypting since. When the host provides it, // writeEnvFileBatchVerified re-reads .env inside the .env lock and refuses // the whole batch unless every pre-read original in expectedOriginals is // still current — closing the lost-update window that would otherwise let // this stale re-encryption silently revert a concurrent admin key save. // Quarantine moves lean on the same guard for their own race: the // expected original for an ORPHANED_V1 slot is "" (absent/empty), so two // workers quarantining different values cannot both win — the loser's // whole batch is refused and retried against the fresh .env. A refusal // takes the same abort path as any failed write (nothing written, nothing // mirrored, retirement untouched); the retry scheduler re-runs the // migration in this process, and the next boot retries too. Legacy deps // (tests) without the verified writer keep the plain locked batch write, // whose own lock still covers its read-modify-write cycle. let saved = false; // True only when the verified writer EXPLICITLY returned false (a // lost-update refusal under the .env lock) rather than throwing or a plain // writer failing — kept apart so the surfaced reason can say "concurrent // modification, the retry will re-read" instead of a generic write failure. // writeEnvFileBatchVerified returns false BOTH for a genuine // concurrent-modification refusal AND for a fail-fast .env.lock-busy, so // "verified-write-refused" deliberately covers both — the retry heals them // identically. let verifiedWriteRefused = false; try { if (typeof deps.writeEnvFileBatchVerified === "function") { saved = deps.writeEnvFileBatchVerified(updates, expectedOriginals) === true; if (!saved) verifiedWriteRefused = true; } else { saved = deps.writeEnvFileBatch(updates) === true; } } catch { saved = false; } if (!saved) { assistantProviderSecretMigrationState.lastFailureReason = verifiedWriteRefused ? ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS.VERIFIED_WRITE_REFUSED : ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS.ENV_WRITE_FAILED; console.warn( "[dashboard-assistant] enc-v1 migration aborted: .env update failed; SECRET_KEY stays an enc-v1 decryption candidate." ); return outcome; } // Mirror the freshly minted envelopes into process.env, like // saveProviderToken does, so readers see the new values immediately. // Quarantine moves mirror too: a null update DELETES the live key from // process.env (the .env line is gone) and the recovery slot receives the // moved envelope verbatim. for (const [envKey, value] of Object.entries(updates)) { if (value === null) delete process.env[envKey]; else process.env[envKey] = value; } // One loud, secret-free console.error per quarantined provider — the // operator must learn that a live slot was emptied into a recovery slot, // how to reverse it, and how to discard it. Names keys, never values. for (const move of quarantinedMoves) { // The move resolved the value's failure history: streak cleared. assistantProviderSecretUndecryptableStreaks.delete(move.liveKey); console.error( `[dashboard-assistant] quarantined an undecryptable legacy enc-v1 key for ${move.providerLabel}: ` + `moved ${move.liveKey} → ${move.orphanKey} after ${move.streak} undecryptable attempt(s). ` + "It could not be decrypted with any configured secret, so it was moved out of the live slot to let the legacy chain retire. " + `Recover: restore the original secret and decrypt ${move.orphanKey} manually. ` + `Discard: delete the ${move.orphanKey} line from .env.` ); } if (migrated > 0) { console.log(`[dashboard-assistant] re-encrypted ${migrated} provider API key(s) as enc-v2 under DASHBOARD_ASSISTANT_ENCRYPTION_SECRET`); } // Retire SECRET_KEY only when .env is now free of enc-v1 values: every // enc-v1 value found was HANDLED — re-wrapped, verified and written, or // quarantined into its empty ORPHANED_V1 recovery slot by this verified // write (enc-v2 values never needed SECRET_KEY, so their state does not // gate the flip; quarantined values are functionally dead and no longer // hold the chain hostage). A partial run (some enc-v1 value skipped — // e.g. its recovery slot is occupied, or its loss is not yet persistent) // leaves the flag — and the full legacy chain — untouched, and the retry // scheduler keeps retrying. outcome.migrated = migrated; if (failed === 0) { assistantProviderSecretV1Retired = true; outcome.retired = true; // Full success: clear the failure history and any pending-retry marker. assistantProviderSecretMigrationState.lastFailureReason = ""; assistantProviderSecretMigrationState.nextRetryAtMs = 0; } else { // Partial run: a dedicated secret was necessarily present (nothing can // be re-wrapped without one), so the residual failures are undecryptable // enc-v1 values, not missing configuration. assistantProviderSecretMigrationState.lastFailureReason = ASSISTANT_PROVIDER_SECRET_MIGRATION_FAILURE_REASONS.UNDECRYPTABLE_VALUE; } return outcome; } // --------------------------------------------------------------------------- // enc-v1 migration retry scheduler (in-process self-healing). // // The migration used to run exactly once per boot: a persistently failing run // (undecryptable value, read-only .env, unavailable dep) silently left the // process in the weak legacy state — provider API keys protected only by the // SECRET_KEY-anchored chain — with a single console.warn as the only signal // until someone happened to restart the panel. The scheduler below keeps the // migration self-healing within the process lifetime instead: every run that // ends with retirement unconfirmed schedules the next run with growing // backoff (30s → 2min → 10min → 30min → 30min …), so a transient condition // (dedicated secret provisioned a tick late, a lost .env-lock race) heals // without a restart, and a persistent one keeps retrying — logging ONE // secret-free console.error line per retry — instead of rotting silently. // For a persistently UNDECRYPTABLE enc-v1 value the retrying ends in // QUARANTINE, not in an eternal loop: once the same value has failed the // quarantine threshold of consecutive runs, the migration moves it to its // ORPHANED_V1 recovery slot and retirement confirms (see the migrate doc // comment); the retry-forever ladder remains only for conditions an operator // must fix (env write access, an occupied recovery slot) or a loss the // process cannot yet prove. // The backoff caps at 30 minutes: rare enough not to spam a broken // environment, prompt enough that fixing .env write access or the dedicated // secret is picked up within half an hour without a redeploy. // --------------------------------------------------------------------------- // Consecutive unretired scheduler-driven runs in this process. Drives both // the backoff index and the "after N attempt(s)" count in the retry error // line; a retired run resets it, so a later degradation starts a fresh // escalation ladder instead of resuming at the cap. let assistantProviderSecretMigrationUnretiredRuns = 0; // Dependency set used by the next run: the most recent // createDashboardAssistantService call wins, so retries always target the // live deps even after the service was reconstructed (hot reload, tests). let assistantProviderSecretMigrationDeps = null; // The single pending retry handle. Deliberately a process-wide singleton: // createDashboardAssistantService may be called several times (tests, hot // reload) and stacked timers would double-run the migration and double-log; // every scheduling path clears the previous handle first. let assistantProviderSecretMigrationRetryTimer = null; // Backoff table for retries after unretired runs; the last entry repeats // indefinitely while retirement stays unconfirmed. const ASSISTANT_PROVIDER_SECRET_MIGRATION_RETRY_DELAYS_MS = Object.freeze([ 30 * 1000, // 30s — catches "the dep was a tick late" startup hiccups 2 * 60 * 1000, 10 * 60 * 1000, 30 * 60 * 1000, // ceiling, repeats ]); function humanizeAssistantProviderSecretMigrationDelay(ms) { if (ms % 60_000 === 0) { const minutes = ms / 60_000; return `${minutes} minute${minutes === 1 ? "" : "s"}`; } const seconds = ms / 1000; return `${seconds} second${seconds === 1 ? "" : "s"}`; } function clearAssistantProviderSecretMigrationRetryTimer() { if (assistantProviderSecretMigrationRetryTimer !== null) { clearTimeout(assistantProviderSecretMigrationRetryTimer); assistantProviderSecretMigrationRetryTimer = null; } } // Note: calling the exported migrateAssistantProviderSecretsV1ToV2 directly // (outside the scheduler) can leave a pending retry timer armed for one extra // self-defusing run; production retirement always runs inside a scheduler run // that consumed its own timer, so this is reachable only from tests/tooling. // Single entry point for every migration run the scheduler triggers (the // immediate first attempt and all retries alike), so the state bookkeeping // and the schedule-or-stop decision live in exactly one place. Returns the // migrate() outcome; never throws. function runAssistantProviderSecretMigrationOnce({ isRetry = false } = {}) { // This run consumes any pending retry: until it concludes there is no // scheduled retry, so the state getter must not advertise one. clearAssistantProviderSecretMigrationRetryTimer(); assistantProviderSecretMigrationState.nextRetryAtMs = 0; let outcome = { retired: false, migrated: 0 }; try { // migrate() itself never throws by contract; this guard only contains // misbehaving host deps. Never crash the worker over a migration. outcome = migrateAssistantProviderSecretsV1ToV2(assistantProviderSecretMigrationDeps) || outcome; } catch { outcome = { retired: false, migrated: 0 }; } // Retirement is one-way (the flag never un-flips), so an unretired outcome // on an already-retired process can only be a re-confirmation edge case // (e.g. the empty-looking-.env run): treat it as success for scheduling — // there is nothing left to heal, and no retry may be scheduled. if (outcome.retired || assistantProviderSecretV1Retired) { assistantProviderSecretMigrationUnretiredRuns = 0; assistantProviderSecretMigrationState.nextRetryAtMs = 0; return outcome; } assistantProviderSecretMigrationUnretiredRuns += 1; const delayMs = ASSISTANT_PROVIDER_SECRET_MIGRATION_RETRY_DELAYS_MS[ Math.min( assistantProviderSecretMigrationUnretiredRuns - 1, ASSISTANT_PROVIDER_SECRET_MIGRATION_RETRY_DELAYS_MS.length - 1 ) ]; assistantProviderSecretMigrationState.nextRetryAtMs = Date.now() + delayMs; // One secret-free console.error line per FAILED retry — the backoff itself // is the rate limit (never more than once per retry run). The first attempt // keeps its historical console.warn-only behavior so existing log // expectations stay stable; it is persistent failure that escalates to // error, starting with the first retry. if (isRetry) { const reason = assistantProviderSecretMigrationState.lastFailureReason || "unknown"; console.error( `[dashboard-assistant] enc-v1 provider key migration still unretired after ${assistantProviderSecretMigrationUnretiredRuns} attempt(s) (reason: ${reason}); retrying in ${humanizeAssistantProviderSecretMigrationDelay(delayMs)}. Provider keys in the legacy envelope remain protected only by the weak legacy chain — fix .env write access / DASHBOARD_ASSISTANT_ENCRYPTION_SECRET and ensure provider keys are re-savable.` ); } assistantProviderSecretMigrationRetryTimer = setTimeout(() => { try { runAssistantProviderSecretMigrationOnce({ isRetry: true }); } catch { // Never crash the worker over a migration retry. } }, delayMs); // unref(): a pending retry must never keep the worker alive — a panel // shutting down (or a test process finishing) must be able to exit // promptly; pm2 restarts re-run the migration from scratch on the next // boot anyway. assistantProviderSecretMigrationRetryTimer.unref(); return outcome; } // Called by createDashboardAssistantService: preserves today's immediate // first attempt (off the boot path, fully guarded) and hands the deps to the // retry scheduler, which keeps re-running the migration until retirement is // confirmed. Last factory call wins on deps; the singleton-timer rule keeps // repeated constructions from stacking retries. function scheduleAssistantProviderSecretMigration(deps) { assistantProviderSecretMigrationDeps = deps; setImmediate(() => { try { runAssistantProviderSecretMigrationOnce({ isRetry: false }); } catch { // Never crash the worker over a migration. } }); } function assistantMessageMentionsPassword(text) { return ( /\b(pass\s?words?|passwd|pwd|pass[- ]?code|parola|parolă)\b/.test(text) || /\b(?:my|the|your|our|account|login|new|current|old)\s+pass\b/.test(text) || /\b(?:change|changing|update|updating|reset|resetting|recover|forgot|lost|edit|switch|rotate|renew|set)\s+(?:my\s+|the\s+|your\s+)?pass\b/.test(text) ); } function assistantMessageMentionsEmail(text) { return ( /\be[- ]?mail(?:s| address)?\b/.test(text) || /\b(?:my|the|account|login)\s+mail(?: address)?\b/.test(text) ); } function assistantMessageMentions2fa(text) { return /\b(2\s?fa|two[-\s]?factor|two[-\s]?step|mfa|totp|otp codes?|one[-\s]?time codes?|authenticator(?: app)?|auth(?:entication)? app)\b/.test(text); } function detectDirectAccountFlowIntent(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return null; const wantsRecovery = /\b(recover|recovery|forgot|forgotten|lost|reset|resetting|locked out|can'?t (?:log|sign)\s?in|cannot (?:log|sign)\s?in|no longer have|don'?t have access|recuperare|recupereaza|recuperează|am uitat|am pierdut|reseteaza|resetează)\b/.test(text); const wantsChange = /\b(change|changing|update|updating|switch|modify|edit|rotate|renew|set|set up|setup|configure|manage|open|show|turn on|turn off|enable|disable|activate|deactivate|add|remove|new|schimb|schimba|schimbă|schimbare|modifica|modifică|seteaza|setează|activeaza|activează|dezactiveaza|dezactivează)\b/.test(text); if (assistantMessageMentionsPassword(text)) { if (wantsRecovery) { return { flow: "recover_password", reply: "Opening password recovery.", }; } if (wantsChange) { return { flow: "change_password", reply: "Opening password change.", }; } } if (assistantMessageMentionsEmail(text)) { if (wantsRecovery) { return { flow: "recover_email", reply: "Opening email recovery.", }; } if (wantsChange) { return { flow: "change_email", reply: "Opening email change.", }; } } if (assistantMessageMentions2fa(text)) { if (wantsRecovery) { return { flow: "recover_2fa", reply: "Opening 2FA recovery.", }; } if (wantsChange) { return { flow: "change_2fa", reply: "Opening 2FA settings.", }; } } return null; } function messageLooksLikeAccountSecurityTopic(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; return ( assistantMessageMentionsPassword(text) || assistantMessageMentions2fa(text) || (assistantMessageMentionsEmail(text) && /\b(change|update|switch|recover|reset|forgot|lost|new|edit|manage)\b/.test(text)) ); } function detectDirectCreateServerFlowIntent(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return null; if (/\b(how|what|which|why|explain|guide|tutorial|cum|ce|care|de ce)\b/.test(text)) { return null; } const wantsCreateServer = ( /\b(create|make|spin\s*up|deploy|provision|start)\b/.test(text) || /\b(can you create|could you create|help me create|let'?s create|i want to create|want to create|wanna create|would like to create)\b/.test(text) || /\b(vreau|vrea|vreau sa|hai sa|te rog)\b/.test(text) || /\b(creez|creeaza|creezi|creare|deschide|arata)\b/.test(text) ) && /\b(server|minecraft|nodejs|python|discord)\b/.test(text); if (!wantsCreateServer) { return null; } return { reply: "Opening the Create Server window.", }; } function detectDirectBulkPowerIntent(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return null; if (/\b(how|what|which|why|explain|guide|tutorial|cum|ce|care|de ce)\b/.test(text)) { return null; } const mentionsServerWords = /\b(server|servers|servere|serverele)\b/.test(text); const mentionsBulkQualifier = /\b(?:all|every|all accessible|all my|all the|toate|toți|toate serverele|toate serverele mele|toate serverele la care am acces)\b/.test(text); const mentionsBulkPronoun = /\b(?:them all|all of them|pe toate)\b/.test(text); const mentionsNonServerTargets = /\b(plugin|plugins|file|files|folder|folders|directory|directories|node|nodes|template|templates)\b/.test(text); const mentionsAllServers = (mentionsServerWords && mentionsBulkQualifier) || (mentionsBulkPronoun && !mentionsNonServerTargets); if (!mentionsAllServers) { return null; } if (/\b(restart|reboot|cycle|bounce|reload|reporneste|repornește)\b/.test(text)) { return { action: "restart" }; } if (/\b(kill|force stop|hard stop|omoara|omoară|ucide)\b/.test(text)) { return { action: "kill" }; } if (/\b(stop|shutdown|shut down|turn off|power off|take down|opreste|oprește|inchide|închide)\b/.test(text)) { return { action: "stop" }; } if (/\b(start|run|boot|turn on|power on|bring up|spin up|porneste|pornește|deschide)\b/.test(text)) { return { action: "start" }; } return null; } function detectAssistantPowerAction(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return ""; if (/\b(restart|reboot|cycle|bounce|reload|reporneste|repornește|da restart)\b/.test(text)) return "restart"; if (/\b(kill|force stop|hard stop|omoara|omoară|ucide|terminate)\b/.test(text)) return "kill"; if (/\b(stop|shutdown|shut down|turn off|power off|take down|opreste|oprește|inchide|închide|da stop)\b/.test(text)) return "stop"; if (/\b(start|run|boot|turn on|power on|bring up|spin up|porneste|pornește|da start)\b/.test(text)) return "start"; return ""; } function detectDirectSinglePowerIntent(message, serverHint = "") { const text = String(message || "").trim(); if (!text) return null; const lower = text.toLowerCase(); if (/\b(how|what|which|why|explain|guide|tutorial|cum|ce|care|de ce)\b/.test(lower)) { return null; } if (detectDirectBulkPowerIntent(text)) { return null; } const hasNonPowerIntent = /\b(file|files|config|folder|directory|log|logs|console|error|backup|plugin|plugins|mod|mods|edit|change|write|read|show|list|inspect|analy[sz]e|fix|debug|server\.properties)\b/i.test(text); if (hasNonPowerIntent) { return null; } const action = detectAssistantPowerAction(text); if (!action) return null; const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim(); if (!server) return null; return { toolName: "power_server", args: { server: text, action }, model: "adpanel-power-router", }; } function messageLooksLikeBusiestLookup(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; const mentionsTarget = /\b(node|nodes|nod|noduri|server|servers|servere|serverele)\b/.test(text); if (!mentionsTarget) return false; // Superlative phrasing is required so questions about one specific server's // load or usage ("teste server, is it good usage?") never route to the // busiest-ranking tool. const asksWhichTarget = /\b(which|what|care|ce)\b/.test(text); const mentionsLoadWords = /\b(busiest|most loaded|highest load|heaviest|cel mai (?:incarcat|încărcat|solicitat|ocupat))\b/.test(text) || (asksWhichTarget && /\b(busy|loaded|load|usage|incarcat|încărcat|solicitat|ocupat)\b/.test(text)); const mentionsSuperlativeMetric = /\b(?:uses?|using|consumes?|consuming|has|with)\s+the\s+most\s+(?:cpu|ram|memory|mem|disk|storage|space)\b/.test(text) || /\b(?:most|highest)\s+(?:cpu|ram|memory|mem|disk|storage|space)\b/.test(text) || /\b(?:cel mai mult|cea mai multa|cea mai multă)\s+(?:cpu|ram|memorie|memory|disk|storage|spatiu|spațiu)\b/.test(text); return mentionsLoadWords || mentionsSuperlativeMetric; } function messageLooksLikeDiagnosisRequest(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; return ( /\b(server|servers|servere|serverele)\b/.test(text) && /\b(diagnose|diagnostic|crash|crashed|crashing|lag|lagging|slow|startup|start up|won'?t start|problem|issue|error|failing|failure|why is|why did|de ce|problema|eroare|a cazut|a căzut)\b/.test(text) ); } function messageLooksLikeConsoleCheckRequest(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; if (messageLooksLikeDiagnosisRequest(text)) return true; const mentionsConsole = /\b(console|logs?|log output|output|latest log|latest logs|startup log|crash log|stderr|stdout|stack trace|traceback)\b/.test(text); const mentionsInspection = /\b(check|check on|show|read|look|inspect|review|scan|analy[sz]e|what|why|tell me|see|look into|figure out)\b/.test(text); const mentionsFailure = /\b(error|errors|crash|crashed|crashing|startup|start up|won'?t start|issue|problem|failing|failure|panic|exception)\b/.test(text); const mentionsStartupTimingOrHealth = /\b(how many seconds|how long(?: did it take)?|startup time|start time|boot time|time to start|took(?: .*?)? to start|startup seconds|started (?:correctly|good|well|fine|okay|ok)|did it start (?:correctly|well|fine|okay|ok)|running well|run(?:ning)? good|run(?:ning)? fine|running okay|came online|is it healthy|is it ok|is it okay|started healthy|fully started|all good|booted|launched)\b/.test(text); return (mentionsConsole && (mentionsInspection || mentionsFailure)) || mentionsStartupTimingOrHealth; } function messageLooksLikeMinecraftBatchPropertyUpdate(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; return ( ( /\bminecraft\b/.test(text) || /\bserver\.properties\b/.test(text) || /\b(online[- ]mode|max[- ]players|motd|pvp|white[- ]list|whitelist|difficulty|view[- ]distance|simulation[- ]distance|spawn[- ]protection|allow[- ]flight|hardcore)\b/.test(text) ) && /\b(all|every|all accessible|all my|them all|all of them|toate|pe toate)\b/.test(text) && /\b(set|change|update|edit|replace|switch|make|put|pune|seteaza|setează|schimba|schimbă|modifica|modifică)\b/.test(text) && ( /\b(server\.properties|properties|config)\b/.test(text) || /[a-z0-9_.-]+\s*(?:=|to|pe)\s*[^\s]+/.test(text) ) ); } function messageLooksLikeStructuredMinecraftPropertyMutation(message) { const text = String(message || "").trim(); if (!text) return false; const lower = text.toLowerCase(); const mentionsMinecraftContext = /\bminecraft\b/.test(lower) || /\bserver\.properties\b/.test(lower) || MINECRAFT_PROPERTY_ALIASES.some((entry) => entry.pattern.test(text)); if (!mentionsMinecraftContext) return false; return /\b(set|change|update|edit|replace|switch|make|put|pune|seteaza|setează|schimba|schimbă|modifica|modifică)\b/i.test(text); } const MINECRAFT_PROPERTY_ALIASES = Object.freeze([ { pattern: /\bonline[- ]mode\b/i, key: "online-mode" }, { pattern: /\bmax[- ]players\b/i, key: "max-players" }, { pattern: /\bview[- ]distance\b/i, key: "view-distance" }, { pattern: /\bsimulation[- ]distance\b/i, key: "simulation-distance" }, { pattern: /\bspawn[- ]protection\b/i, key: "spawn-protection" }, { pattern: /\ballow[- ]flight\b/i, key: "allow-flight" }, { pattern: /\bwhite[- ]list\b/i, key: "white-list" }, { pattern: /\bwhitelist\b/i, key: "white-list" }, { pattern: /\bmotd\b/i, key: "motd" }, { pattern: /\bdifficulty\b/i, key: "difficulty" }, { pattern: /\bpvp\b/i, key: "pvp" }, { pattern: /\bhardcore\b/i, key: "hardcore" }, ]); function inferAssistantMetric(message) { const text = String(message || "").trim().toLowerCase(); if (/\bcpu\b/.test(text)) return "cpu"; if (/\b(memory|ram)\b/.test(text)) return "memory"; if (/\b(disk|storage|space)\b/.test(text)) return "disk"; return "balanced"; } function inferAssistantMetricDetails(message) { const text = String(message || "").trim().toLowerCase(); const includeMetrics = []; if (/\bcpu\b/.test(text)) includeMetrics.push("cpu"); if (/\b(memory|ram)\b/.test(text)) includeMetrics.push("memory"); if (/\b(disk|storage|space)\b/.test(text)) includeMetrics.push("disk"); return { metric: includeMetrics.length === 1 ? includeMetrics[0] : "balanced", includeMetrics, }; } function detectDirectLoadLookupIntent(message) { const text = String(message || "").trim().toLowerCase(); if (!text || !messageLooksLikeBusiestLookup(text)) return null; const metricDetails = inferAssistantMetricDetails(text); const mentionsNode = /\b(node|nodes|nod|noduri)\b/.test(text); const mentionsServer = /\b(server|servers|servere|serverele)\b/.test(text); if (mentionsNode) { return { toolName: "get_busiest_node", args: { metric: metricDetails.metric, includeMetrics: metricDetails.includeMetrics }, model: "adpanel-load-router", }; } if (mentionsServer) { return { toolName: "get_busiest_server", args: { metric: metricDetails.metric, includeMetrics: metricDetails.includeMetrics }, model: "adpanel-load-router", }; } return null; } function detectDirectConsoleCheckIntent(message, serverHint = "") { const text = String(message || "").trim(); if (!text) return null; const looksLikeConsoleCheck = messageLooksLikeConsoleCheckRequest(text) || (!!serverHint && /\b(console|logs?|log output|startup|crash|error|errors|why|diagnose|issue|problem|failing|failure|started|seconds?|healthy|running well|running fine|running okay|took to start|time to start|boot time|startup time|start time|started good|started well|started fine|started okay|started ok|all good|booted|launched)\b/i.test(text)); if (!looksLikeConsoleCheck) return null; const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim() || text; return { toolName: "check_server_console", args: { server, question: text }, model: "adpanel-console-router", }; } function messageLooksLikeServerLimitsCheckRequest(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; if (messageLooksLikeBusiestLookup(text)) return false; if (messageLooksLikeAssistantOpenRequest(text)) return false; if (messageLooksLikeConsoleCheckRequest(text)) return false; const mentionsMetric = /\b(cpu|ram|memory|disk|storage|space|resource(?:s| stats?)?|quota|quotas|limit|limits|headroom|free|remaining|left|available|usage|used)\b/.test(text); const mentionsInspection = /\b(check|show|see|tell me|what|how much|how many|look|inspect|review|analy[sz]e|is|are|close|near|almost|running out|enough)\b/.test(text); const mentionsPressure = /\b(close to|near(?:ly)? full|almost full|very high|too high|running out|low on|full|running hot|saturated|overloaded|healthy|okay|ok|fine)\b/.test(text); return mentionsMetric && (mentionsInspection || mentionsPressure); } function detectDirectServerLimitsIntent(message, serverHint = "") { const text = String(message || "").trim(); if (!text) return null; const looksLikeLimitsCheck = messageLooksLikeServerLimitsCheckRequest(text) || (!!serverHint && /\b(cpu|ram|memory|disk|storage|space|quota|quotas|limit|limits|headroom|free|remaining|left|available|close to|near full|almost full|too high)\b/i.test(text)); if (!looksLikeLimitsCheck) return null; const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim(); if (!server) return null; const metricDetails = inferAssistantMetricDetails(text); return { toolName: "check_server_limits", args: { server, question: text, includeMetrics: metricDetails.includeMetrics, }, model: "adpanel-limits-router", }; } function messageLooksLikeAssistantOpenRequest(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; return /\b(open|show|take me|go to|goto|navigate|bring me|launch|pop ?up|new tab|tab|manage|configure|config|edit|access)\b/.test(text); } function messageLooksLikeServerInfoRequest(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; if (messageLooksLikeBusiestLookup(text)) return false; if (messageLooksLikeConsoleCheckRequest(text)) return false; if (messageLooksLikeServerLimitsCheckRequest(text)) return false; if (messageLooksLikeAssistantOpenRequest(text)) return false; const mentionsFact = /\b(template|templates|image|ip|address|port|ports|node|nodes|version|fork|backups?|details?|info|information|overview|specs?|specifications?)\b/.test(text); const mentionsInquiry = /\b(what|whats|what's|which|where|who|when|how many|how much|tell me|is|are|does|do|has|have|on what|on which|running|runs?|pe ce|ce|care|cate|câte)\b/.test(text); return mentionsFact && mentionsInquiry; } function detectDirectServerInfoIntent(message, serverHint = "") { const text = String(message || "").trim(); if (!text) return null; if (!messageLooksLikeServerInfoRequest(text)) return null; const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim(); if (!server) return null; return { toolName: "get_server_overview", args: { server, question: text }, model: "adpanel-server-info-router", }; } function normalizeAssistantServerPageSection(value) { const text = normalizeAssistantLookupText(value); if (!text) return "console"; if (/\b(backups?|snapshots?)\b/.test(text)) return "backups"; if (/\b(files?|file manager|explorer|folders?|directory|directories)\b/.test(text)) return "files"; if (/\b(activity|history|events?)\b/.test(text)) return "activity"; if (/\b(scheduler|schedule|schedules|tasks?)\b/.test(text)) return "scheduler"; if (/\b(store|plugins?|versions?|marketplace)\b/.test(text)) return "store"; if (/\b(resource(?:s| stats?)?|cpu|ram|memory|disk|storage)\b/.test(text)) return "resource_stats"; if (/\b(reinstall|rebuild|reimage|re-image)\b/.test(text)) return "reinstall"; if (/\b(ai help|assistant help)\b/.test(text)) return "ai_help"; if (/\b(info|overview|details?)\b/.test(text)) return "info"; return "console"; } function formatAssistantServerPageSectionLabel(section) { const key = String(section || "").trim(); return ASSISTANT_SERVER_PAGE_SECTION_LABELS[key] || "server page"; } function normalizeAssistantSettingsAction(value) { const text = normalizeAssistantLookupText(value); if (!text) return ""; if (/\b(pgadmin|postgres setup|postgresql setup)\b/.test(text)) return "pgadmin_setup"; if (/\b(mongodb|mongo setup)\b/.test(text)) return "mongodb_setup"; if (/\b(create|new|add)\b.*\buser\b/.test(text)) return "create_user"; if (/\bbranding\b/.test(text)) return "branding"; if (/\blogin background\b/.test(text)) return "login_background"; if (/\b(alert|announcement|banner|global alert)\b/.test(text)) return "alert"; if (/\b(database setup|setup database|set up database|phpmyadmin|mysql setup)\b/.test(text)) return "database_setup"; if (/\bcaptcha\b/.test(text)) return "captcha"; if (/\bmaintenance\b/.test(text)) return "maintenance"; if (/\b(create|new|add)\b.*\bnode\b/.test(text)) return "create_node"; if (/\b(create|new|add)\b.*\btemplate\b/.test(text)) return "create_template"; if ((/\b(add|create|new)\b/.test(text) || /\bpopup\b|\bmodal\b/.test(text)) && /\bwebhook\b/.test(text)) return "add_webhook"; return ""; } function inferAssistantSettingsPanelFromAction(action) { const normalized = String(action || "").trim(); if (!normalized) return ""; if (["branding", "login_background"].includes(normalized)) return "customization"; if (["create_user"].includes(normalized)) return "account"; if (["captcha", "maintenance"].includes(normalized)) return "security"; if (["database_setup", "pgadmin_setup", "mongodb_setup"].includes(normalized)) return "databases"; if (["create_node"].includes(normalized)) return "nodes"; if (["create_template"].includes(normalized)) return "templates"; if (["add_webhook"].includes(normalized)) return "webhooks"; if (["alert"].includes(normalized)) return "customization"; return ""; } function normalizeAssistantSettingsPanel(value) { const text = normalizeAssistantLookupText(value); if (!text) return ""; if (/\b(panel info|panelinfo)\b/.test(text)) return "panelinfo"; if (/\b(customization|customisation|appearance|look|theme|style|branding)\b/.test(text)) return "customization"; if (/\b(account|accounts?|users?|user management)\b/.test(text)) return "account"; if (/\b(security|captcha|maintenance)\b/.test(text)) return "security"; if (/\b(databases?|database|db|mysql|postgres|postgresql|pgadmin|mongo|mongodb)\b/.test(text)) return "databases"; if (/\b(nodes?|infrastructure)\b/.test(text)) return "nodes"; if (/\b(templates?|docker templates?)\b/.test(text)) return "templates"; if (/\b(servers?|instances?)\b/.test(text)) return "servers"; if (/\b(webhooks?|discord)\b/.test(text)) return "webhooks"; if (/\b(preferences?|general settings?|settings home)\b/.test(text)) return "preferences"; return ""; } function formatAssistantSettingsPanelLabel(panel) { const key = String(panel || "").trim(); return ASSISTANT_SETTINGS_PANEL_LABELS[key] || "Settings"; } function formatAssistantSettingsActionLabel(action) { const key = String(action || "").trim(); return ASSISTANT_SETTINGS_ACTION_LABELS[key] || "that settings tool"; } function extractAssistantUrlsFromText(value) { return Array.from(String(value || "").matchAll(/https?:\/\/[^\s<>"')]+/gi)) .map((match) => String(match?.[0] || "").replace(/[.,!?;:]+$/g, "").trim()) .filter(Boolean); } function parseAssistantServerSectionFromUrlAction(value) { const action = String(value || "").trim().toLowerCase(); const map = { "open-info": "info", "open-files": "files", "open-activity": "activity", "open-backups": "backups", "open-scheduler": "scheduler", "open-store": "store", "open-resource-stats": "resource_stats", "open-reinstall": "reinstall", "open-ai-help": "ai_help", }; return map[action] || "console"; } function parseAssistantNavigationContextFromUrl(rawUrl) { const urlText = String(rawUrl || "").trim(); if (!urlText) return null; try { const parsed = new URL(urlText); if (parsed.pathname === "/settings") { const action = normalizeAssistantSettingsAction(parsed.searchParams.get("assistantAction") || ""); const panel = normalizeAssistantSettingsPanel(parsed.searchParams.get("panel") || "") || (action ? inferAssistantSettingsPanelFromAction(action) : ""); if (panel || action) { return { kind: "settings", panel, action, }; } } const serverMatch = parsed.pathname.match(/^\/server\/([^/?#]+)/i); if (serverMatch?.[1]) { return { kind: "server", server: sanitizeToken(decodeURIComponent(serverMatch[1] || "")), section: parseAssistantServerSectionFromUrlAction(parsed.searchParams.get("assistantAction") || ""), }; } } catch { } return null; } function getRecentAssistantNavigationContext(conversationHistory = []) { const recentHistory = Array.isArray(conversationHistory) ? conversationHistory.slice(-12) : []; for (let index = recentHistory.length - 1; index >= 0; index -= 1) { const content = normalizeMessageContent(recentHistory[index]?.content); const urls = extractAssistantUrlsFromText(content); for (let urlIndex = urls.length - 1; urlIndex >= 0; urlIndex -= 1) { const parsed = parseAssistantNavigationContextFromUrl(urls[urlIndex]); if (parsed) return parsed; } } return null; } function isShortAssistantNavigationShortcut(message) { const text = normalizeAssistantLookupText(message); if (!text || text.length > 48) return false; if (text.split(" ").filter(Boolean).length > 4) return false; return !/[?]/.test(String(message || "")); } function messageExplicitlyNamesAssistantServerSection(message) { return /\b(console|terminal|logs?|backups?|files?|activity|scheduler|tasks?|store|plugins?|versions?|resource(?:s| stats?)?|overview|info|details?|reinstall|ai help|assistant help)\b/i.test(String(message || "")); } function messageExplicitlyNamesAssistantSettingsDestination(message) { return /\b(settings?|preferences?|appearance|customization|account|security|databases?|db|nodes?|templates?|servers?|webhooks?|panel info|branding|background|captcha|maintenance|create user|create node|create template|pgadmin|mongodb|webhook)\b/i.test(String(message || "")); } function detectDirectOpenServerPageIntent(message, serverHint = "", conversationHistory = []) { const text = String(message || "").trim(); if (!text) return null; const recentNavigationContext = getRecentAssistantNavigationContext(conversationHistory); const shortNavigationShortcut = isShortAssistantNavigationShortcut(text); if (!messageLooksLikeAssistantOpenRequest(text) && !(shortNavigationShortcut && recentNavigationContext?.kind === "server")) return null; if (/\bsettings?\b/i.test(text)) return null; const mentionsServerArea = messageExplicitlyNamesAssistantServerSection(text) || /\b(server|page)\b/i.test(text); if (!mentionsServerArea) return null; const extractedServer = extractAssistantServerCandidate(text); const recentServer = recentNavigationContext?.kind === "server" ? String(recentNavigationContext.server || "").trim() : ""; const server = !isWeakAssistantServerReference(extractedServer) ? extractedServer : (String(serverHint || "").trim() || recentServer); if (!server) return null; return { toolName: "open_server_page", args: { server, section: normalizeAssistantServerPageSection(text), }, model: "adpanel-navigation-router", }; } function detectDirectOpenSettingsIntent(message, conversationHistory = []) { const text = String(message || "").trim(); if (!text) return null; const recentNavigationContext = getRecentAssistantNavigationContext(conversationHistory); const normalizedPanel = normalizeAssistantSettingsPanel(text); const normalizedAction = normalizeAssistantSettingsAction(text); if (!normalizedPanel && !normalizedAction) return null; if ( normalizedPanel === "servers" && !/\bsettings?\b/i.test(text) && ( messageExplicitlyNamesAssistantServerSection(text) || /\bfor\s+(?:a|an|the|that|this)?\s*server\b/i.test(text) ) ) { return null; } const shortNavigationShortcut = isShortAssistantNavigationShortcut(text); if ( !messageLooksLikeAssistantOpenRequest(text) && !/\bsettings?\b/i.test(text) && !shortNavigationShortcut && recentNavigationContext?.kind !== "settings" ) { return null; } return { toolName: "open_settings_destination", args: { panel: normalizedPanel || inferAssistantSettingsPanelFromAction(normalizedAction), action: normalizedAction, }, model: "adpanel-settings-router", }; } function cleanAssistantServerCandidate(value) { let candidate = String(value || "") .replace(/^[`"'“”‘’([{<\s]+/g, "") .replace(/[`"'“”‘’)\]}>]+$/g, "") .replace(/[.,!?;:]+$/g, "") .trim(); if (!candidate) return ""; candidate = candidate .replace(/\b(?:if|when|daca|dacă|and|then|si|și|restart|reboot|reporn(?:e|i)ste|repornește|restarteaza|restartează)\b.*$/i, " ") .replace(/\b(?:a|an|the|my|our|please|pls|now|right|server|servers|servere|serverele|named|called|target|crash|crashed|crashing|lag|lagging|issue|issues|problem|problema|startup|start up|error|errors|failing|failure|why|did|de|ce|căzut|cazut)\b/gi, " ") .replace(/\b(?:storage|disk|space|ram|memory|mem|cpu|usage|used|using|limits?|quota|quotas|headroom|free|left|remaining|available|consume[sd]?|good|bad|ok|okay|fine|much|many|how|is|it|about)\b/gi, " ") .replace(/\b(?:what|whats|which|where|who|when|does|do|has|have|template|templates|ip|address|port|ports|node|nodes|version|versions|fork|backups?|info|information|details?|overview|specs?|running|runs?)\b/gi, " ") .replace(/\s+/g, " ") .trim(); if (!candidate) return ""; if (/^(?:a|an|it|them|that|this|one|all)$/i.test(candidate)) return ""; return candidate; } function extractAssistantServerCandidate(message) { const raw = String(message || "").trim(); if (!raw) return ""; const quoted = raw.match(/["'`“”]([^"'`“”]{1,80})["'`“”]/); if (quoted) { const candidate = cleanAssistantServerCandidate(quoted[1]); if (candidate) return candidate; } const wrappedMatches = Array.from(raw.matchAll(/[\(\[]([^()\[\]]{1,80})[\)\]]/g)); for (const match of wrappedMatches) { const candidate = cleanAssistantServerCandidate(match[1]); if (candidate) return candidate; } const patterns = [ /\bserver(?:ul)?\s+([a-z0-9][a-z0-9._-]*(?:\s+[a-z0-9][a-z0-9._-]*){0,2})/i, /\b(?:srv|bot)\s+([a-z0-9][a-z0-9._-]*(?:\s+[a-z0-9][a-z0-9._-]*){0,2})/i, /\b(?:for|on|la|pe)\s+server(?:ul)?\s+([a-z0-9][a-z0-9._-]*(?:\s+[a-z0-9][a-z0-9._-]*){0,2})/i, /\b(?:for|on|about|check|diagnose|inspect|why did|why is|problema la|de ce a cazut|de ce a căzut)\s+([a-z0-9][a-z0-9._-]*(?:\s+[a-z0-9][a-z0-9._-]*){0,2})/i, /\b(?:start|run|boot|turn on|power on|bring up|spin up|restart|reboot|cycle|bounce|reload|stop|shutdown|shut down|turn off|power off|take down|kill|terminate|porneste|pornește|opreste|oprește|inchide|închide|reporneste|repornește|omoara|omoară|ucide)\s+([a-z0-9][a-z0-9._-]*(?:\s+[a-z0-9][a-z0-9._-]*){0,2})/i, ]; for (const pattern of patterns) { const match = raw.match(pattern); if (!match) continue; const candidate = cleanAssistantServerCandidate(match[1]); if (candidate) return candidate; } return ""; } function detectDirectDiagnosisIntent(message, serverHint = "") { const text = String(message || "").trim(); if (!text) return null; const looksLikeDiagnosis = messageLooksLikeDiagnosisRequest(text) || (!!serverHint && /\b(diagnose|diagnostic|crash|crashed|crashing|lag|lagging|slow|startup|start up|won'?t start|problem|issue|error|failing|failure|why is|why did|de ce|problema|eroare|a cazut|a căzut)\b/i.test(text)); if (!looksLikeDiagnosis) return null; const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim(); if (!server) return null; return { toolName: "diagnose_server", args: { server }, model: "adpanel-diagnosis-router", }; } function normalizeMinecraftPropertyKey(value) { const clean = String(value || "").trim(); if (/^[A-Za-z0-9._-]+$/.test(clean)) return clean; for (const entry of MINECRAFT_PROPERTY_ALIASES) { if (entry.pattern.test(clean)) { return entry.key; } } return ""; } function trimMinecraftPropertyValueSegment(value) { let clean = String(value || "").trim(); if (!clean) return ""; clean = clean .split(/\s+\b(?:for|on|pe|la)\b\s+(?:all|every|all accessible|all my|them all|all of them|toate|pe toate|server(?:ul)?|servers|servere|serverele|minecraft)\b/i)[0] .replace(/\s+\b(?:only if|doar daca|doar dacă)\b[\s\S]*$/i, "") .replace(/\s+\b(?:if|when|daca|dacă)\b[\s\S]*$/i, "") .replace(/\s+\b(?:and|then|si|și)\b\s+(?:restart|reboot|reporn(?:e|i)ste|repornește|restarteaza|restartează)\b[\s\S]*$/i, "") .replace(/\s+\b(?:after(?:wards)?|after that|după|dupa)\b[\s\S]*$/i, "") .trim(); return clean; } function normalizeMinecraftPropertyValue(value) { let clean = trimMinecraftPropertyValueSegment(value); if (!clean) return ""; clean = clean .replace(/^[`"'“”‘’]+|[`"'“”‘’]+$/g, "") .replace(/^[:=]\s*/g, "") .replace(/[.,!?;:]+$/g, "") .replace(/^(?:is|este|e)\s+/i, "") .trim(); if (/^(true|on|enabled?|yes|da)$/i.test(clean)) return "true"; if (/^(false|off|disabled?|no|nu)$/i.test(clean)) return "false"; return clean.slice(0, 160); } function extractMinecraftConditionalCurrentValue(message) { const text = String(message || "").trim(); if (!text) return ""; const patterns = [ /\b(?:if|when)\s+(?:it(?:'s| is)?|the current value is|current value is)?\s*(true|false|on|off|enabled?|disabled?|yes|no)\b/i, /\b(?:only if)\s+(?:it(?:'s| is)?|the current value is|current value is)?\s*(true|false|on|off|enabled?|disabled?|yes|no)\b/i, /\b(?:daca|dacă)\s+(?:e|este)?\s*(true|false|on|off|enabled?|disabled?|yes|no|da|nu)\b/i, /\b(?:doar daca|doar dacă)\s+(?:e|este)?\s*(true|false|on|off|enabled?|disabled?|yes|no|da|nu)\b/i, ]; for (const pattern of patterns) { const match = text.match(pattern); if (!match) continue; const normalized = normalizeMinecraftPropertyValue(match[1]); if (normalized) return normalized; } return ""; } function messageRequestsRestartAfterPropertyUpdate(message) { const text = String(message || "").trim(); if (!text) return false; return /\b(restart|reboot|reporn(?:e|i)ste|repornește|restarteaza|restartează)\b/i.test(text); } function stripTrailingServerHintFromValue(value, serverHint) { const cleanValue = String(value || "").trim(); const cleanServer = String(serverHint || "").trim(); if (!cleanValue || !cleanServer) return cleanValue; const normalizedTokens = normalizeAssistantLookupText(cleanServer).split(" ").filter(Boolean); if (!normalizedTokens.length) return cleanValue; const flexibleServerPattern = normalizedTokens.map((token) => escapeRegex(token)).join("[\\s._-]+"); return cleanValue .replace(new RegExp(`\\s+(?:on|for|pe|la)\\s+${flexibleServerPattern}\\s*$`, "i"), "") .trim(); } function extractChainedPowerAction(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return ""; if (!/\b(and|then|after|afterwards|after that|si|și|apoi|după|dupa|la final|cand termini|când termini|when done)\b/.test(text)) { return ""; } return detectAssistantPowerAction(text); } function extractMinecraftPropertyValue(message, propertyKey) { const raw = String(message || "").trim(); if (!raw || !propertyKey) return ""; const exactPattern = new RegExp(`\\b${escapeRegex(propertyKey)}\\b\\s*(?::|=|to|pe|as|la)?\\s*([^\\n]+)`, "i"); const exactMatch = raw.match(exactPattern); if (exactMatch) { const exactValue = normalizeMinecraftPropertyValue(exactMatch[1]); if (exactValue) return exactValue; } const aliasEntry = MINECRAFT_PROPERTY_ALIASES.find((entry) => entry.key === propertyKey); if (!aliasEntry) return ""; const aliasMatch = raw.match(aliasEntry.pattern); if (!aliasMatch || typeof aliasMatch.index !== "number") return ""; const remainder = raw.slice(aliasMatch.index + aliasMatch[0].length) .replace(/^\s*(?:to|=|pe|as|la)\s*/i, "") .trim(); if (!remainder) return ""; if (/^["'`“”]/.test(remainder)) { const quoted = remainder.match(/^[`"'“”]([^`"'“”]{1,160})[`"'“”]/); if (quoted) return normalizeMinecraftPropertyValue(quoted[1]); } return normalizeMinecraftPropertyValue( remainder ); } function detectDirectMinecraftPropertyIntent(message, serverHint = "") { const text = String(message || "").trim(); if (!text) return null; if (!messageLooksLikeStructuredMinecraftPropertyMutation(text)) return null; const wantsAll = /\b(all|every|all accessible|all my|them all|all of them|toate|pe toate)\b/i.test(text); const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim(); const scope = wantsAll ? "all_accessible_minecraft" : (server ? "single_server" : ""); if (!scope) return null; const propertyFromAssignment = text.match(/\b([a-z0-9._-]+)\b\s*(?:=|:)\s*([^\n]+)/i); const property = normalizeMinecraftPropertyKey(propertyFromAssignment?.[1] || text); const rawValue = propertyFromAssignment?.[2] || extractMinecraftPropertyValue(text, property); const value = normalizeMinecraftPropertyValue(stripTrailingServerHintFromValue(rawValue, server)); const onlyIfCurrent = extractMinecraftConditionalCurrentValue(text); const restartAfter = messageRequestsRestartAfterPropertyUpdate(text); if (!property || !value) return null; return { toolName: "update_minecraft_server_property", args: scope === "single_server" ? { property, value, scope, server, ...(onlyIfCurrent ? { onlyIfCurrent } : {}), ...(restartAfter ? { restartAfter: true } : {}) } : { property, value, scope, ...(onlyIfCurrent ? { onlyIfCurrent } : {}), ...(restartAfter ? { restartAfter: true } : {}) }, model: "adpanel-minecraft-router", }; } function cleanAssistantPathCandidate(value) { let candidate = String(value || "") .replace(/^[`"'“”‘’]+|[`"'“”‘’]+$/g, "") .replace(/[),.!?;:]+$/g, "") .trim(); candidate = candidate .replace(/^(?:file|path|folder|directory|config)\s+/i, "") .replace(/\\/g, "/") .replace(/^\.\/+/, "") .replace(/^\/+/, "") .trim(); if (!candidate || candidate === "." || candidate === "..") return ""; return candidate.slice(0, 220); } function extractAssistantFilePath(message) { const raw = String(message || "").trim(); if (!raw) return ""; const quotedMatches = Array.from(raw.matchAll(/[`"'“”]([^`"'“”]{1,220})[`"'“”]/g)); for (const match of quotedMatches) { const candidate = cleanAssistantPathCandidate(match[1]); if (/[/.]/.test(candidate) || /\.[A-Za-z0-9]{1,12}$/.test(candidate)) { return candidate; } } const knownFileMatch = raw.match(/\b(server\.properties|eula\.txt|package\.json|docker-compose\.ya?ml|requirements\.txt|pyproject\.toml|cargo\.toml|dockerfile|makefile|(?:index|main|app)\.(?:js|ts|mjs|cjs|py)|config\.(?:ya?ml|json|toml|ini|cfg)|latest\.log|\.env|plugins|mods|config|logs|crash-reports)\b/i); if (knownFileMatch) { return cleanAssistantPathCandidate(knownFileMatch[1]); } const pathMatch = raw.match(/(?:^|[\s(])([A-Za-z0-9._-]+(?:\/[A-Za-z0-9._ -]+)+\/?)(?=$|[\s),.!?])/); if (pathMatch) { return cleanAssistantPathCandidate(pathMatch[1]); } const flatFileMatch = raw.match(/(?:^|[\s(])([A-Za-z0-9._-]+\.[A-Za-z0-9]{1,12})(?=$|[\s),.!?])/); if (flatFileMatch) { return cleanAssistantPathCandidate(flatFileMatch[1]); } return ""; } function looksLikeAssistantDirectoryPath(filePath) { const clean = cleanAssistantPathCandidate(filePath); if (!clean) return false; if (clean.endsWith("/")) return true; const base = clean.split("/").filter(Boolean).pop() || ""; return !/\.[A-Za-z0-9]{1,12}$/i.test(base); } function detectDirectFileInspectIntent(message, serverHint = "") { const text = String(message || "").trim(); if (!text) return null; const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim(); const path = extractAssistantFilePath(text); if (!server || !path) return null; const lower = text.toLowerCase(); const wantsFileContext = /[/.]/.test(path) || /\b(file|files|folder|directory|config|log|logs|path|server\.properties|eula|package\.json)\b/.test(lower); if (!wantsFileContext) return null; const wantsInspection = /\b(read|show|open|view|check|inspect|look at|see|vezi|arata|arată|deschide|what'?s in|what is in|analy[sz]e|review|ce sa vad|ce să văd)\b/i.test(text); const wantsAdvice = /\b(what should i change|what to change|ce sa schimb|ce să schimb)\b/i.test(text); if (!wantsInspection && !wantsAdvice) return null; const toolName = looksLikeAssistantDirectoryPath(path) && /\b(list|show|see|inside|contents?|explore|browse)\b/i.test(text) ? "list_files" : "read_file"; return { toolName, args: { server, path }, model: "adpanel-file-router", }; } function messageNeedsRealActionExecution(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; const createServerIntent = /\b(create|make|spin\s*up|deploy|provision)\b/.test(text) && /\b(server|minecraft|nodejs|python|discord|template|templates|node|nodes)\b/.test(text); if (createServerIntent) return true; const pluginInstallIntent = /\b(install|add|download|setup|set up)\b/.test(text) && /\b(plugin|plugins|modrinth|viaversion|geyser|luckperms|vault)\b/.test(text); if (pluginInstallIntent) return true; const deleteServerIntent = /\b(delete|remove|destroy|wipe)\b/.test(text) && /\b(server|servers)\b/.test(text); if (deleteServerIntent) return true; const serverPowerIntent = /\b(start|stop|restart|kill|power|porneste|pornește|opreste|oprește|inchide|închide|omoara|omoară|ucide|reporneste|repornește)\b/.test(text) && /\b(server|servers|servere|serverele)\b/.test(text); if (serverPowerIntent) return true; if (detectAssistantPowerAction(text) && extractAssistantServerCandidate(text)) return true; if (messageLooksLikeBusiestLookup(text)) return true; if (messageLooksLikeDiagnosisRequest(text)) return true; if (messageLooksLikeStructuredMinecraftPropertyMutation(text)) return true; const fileMutationIntent = /\b(edit|write|replace|overwrite|append|create|delete|remove|rename|move|mkdir|make)\b/.test(text) && /\b(file|files|folder|directory|config|properties|server\.properties|eula|plugin|plugins|world|mods?)\b/.test(text); if (fileMutationIntent) return true; if (messageLooksLikeMinecraftBatchPropertyUpdate(text)) return true; const explicitPathMutation = /\b(edit|write|replace|overwrite|append|create|delete|remove|rename|move|mkdir|make)\b/.test(text) && /[./\\][\w./\\-]+/.test(text); if (explicitPathMutation) return true; return false; } function replyClaimsActionSucceeded(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; if (/[?]/.test(text)) return false; if (/\b(i need|need one more detail|which|what|tell me|choose|pick|do you want|would you like|please provide|cannot|can't|do not have permission|don't have permission|failed|error)\b/.test(text)) { return false; } return /\b(done|completed|created|started|stopped|restarted|killed|updated|deleted|removed|renamed|moved|written|saved|applied|opened|opening)\b/.test(text); } function shouldAllowToolUseForMessage(message, conversationHistory = []) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; const recentHistory = Array.isArray(conversationHistory) ? conversationHistory.slice(-8) : []; const lastAssistantMessage = recentHistory .slice() .reverse() .find((entry) => String(entry?.role || "").toLowerCase() === "assistant"); const lastAssistantText = normalizeMessageContent(lastAssistantMessage?.content).toLowerCase(); const assistantAskedStructuredFollowUp = /\b(which|what|how much|how many|choose|pick|tell me|do you want|would you like)\b/.test(lastAssistantText) && /\b(template|templates|node|nodes|server name|name|ram|cpu|storage|port|password|email|2fa|two[- ]factor|recovery|file|path|plugin|plugins|loader|platform|minecraft version|version)\b/.test(lastAssistantText); const assistantAskedActionConfirmation = /\b(ready|want me to|should i|go ahead|create it|create the server|apply it|use that|use this)\b/.test(lastAssistantText) && /\b(server|template|node|port|ram|cpu|storage|create|provision)\b/.test(lastAssistantText); const shortStructuredReply = text.length <= 80 && ( isAffirmativeShortReply(text) || /^(that one|this one)$/i.test(String(text || "").trim()) || /^\d{2,5}$/.test(text) || /\b\d+(?:\.\d+)?\s*(?:mb|gb|tb|cores?)\b/.test(text) || /\b(?:port|ram|cpu|storage|node|template|plugin|loader|platform|paper|purpur|spigot|bukkit|velocity|fabric|forge|neoforge)\b/.test(text) ); const infrastructureShortcut = /^(nodes?|templates?|servers?)$/.test(text); if (infrastructureShortcut) return true; const accountIntent = /\b(change|reset|recover|update|open|show)\b/.test(text) && /\b(password|email|2fa|two[- ]factor|recovery|recovery code|recovery codes)\b/.test(text); if (accountIntent) return true; const explicitServerListing = /\b(list|show|which|what)\b/.test(text) && /\b(server|servers|node|nodes)\b/.test(text); if (explicitServerListing) return true; const explicitTemplateOrNodeListing = /\b(list|show|which|what)\b/.test(text) && /\b(template|templates|node|nodes)\b/.test(text); if (explicitTemplateOrNodeListing) return true; const serverQuestion = /\b(status|port|template|permission|permissions|ip|uptime|online|offline|running|stopped|console)\b/.test(text) && /\b(?:server|servers|node|nodes)\b/.test(text); if (serverQuestion) return true; if (messageLooksLikeBusiestLookup(text)) return true; if (messageLooksLikeDiagnosisRequest(text)) return true; const createServerIntent = /\b(create|make|spin\s*up|deploy|provision)\b/.test(text) && /\b(server|minecraft|nodejs|python|discord|template|templates|node|nodes)\b/.test(text); if (createServerIntent) return true; const pluginInstallIntent = /\b(install|add|download|setup|set up)\b/.test(text) && /\b(plugin|plugins|modrinth|viaversion|geyser|luckperms|vault)\b/.test(text); if (pluginInstallIntent) return true; const deleteServerIntent = /\b(delete|remove|destroy|wipe)\b/.test(text) && /\b(server|servers)\b/.test(text); if (deleteServerIntent) return true; const fileOrServerAction = /\b(start|stop|restart|kill|power|edit|read|write|create|delete|remove|rename|move|open|inspect|list|show|porneste|pornește|opreste|oprește|inchide|închide|omoara|omoară|ucide|reporneste|repornește|citeste|citește|scrie|editeaza|editează|sterge|șterge|arata|arată)\b/.test(text) && /\b(server|servers|servere|serverele|file|files|folder|directory|config|properties|server\.properties|eula|plugin|plugins|world|mods?)\b/.test(text); if (fileOrServerAction) return true; if (messageLooksLikeMinecraftBatchPropertyUpdate(text)) return true; const explicitPathAction = /\b(read|write|edit|create|delete|rename|move|list|show)\b/.test(text) && /[./\\][\w./\\-]+/.test(text); if (explicitPathAction) return true; if (assistantAskedStructuredFollowUp) { return true; } if (assistantAskedActionConfirmation && shortStructuredReply) { return true; } return false; } function getLastAssistantText(conversationHistory = []) { const recentHistory = Array.isArray(conversationHistory) ? conversationHistory.slice(-10) : []; const lastAssistantMessage = recentHistory .slice() .reverse() .find((entry) => String(entry?.role || "").toLowerCase() === "assistant"); return normalizeMessageContent(lastAssistantMessage?.content).trim(); } function buildCarryForwardVisibleTranscript(messages, options = {}) { const recentMessages = (Array.isArray(messages) ? messages : []) .filter((entry) => entry && (entry.role === "user" || entry.role === "assistant")) .slice(-Math.max(1, Number(options.count) || 18)); if (!recentMessages.length) return ""; const perMessageLimit = Math.max(60, Number(options.perMessageLimit) || 220); const totalLimit = Math.max(400, Number(options.totalLimit) || 2600); const lines = []; for (const entry of recentMessages) { const role = String(entry.role || "").toLowerCase() === "user" ? "User" : "Assistant"; const content = normalizeMessageContent(entry.content) .replace(/\s+/g, " ") .trim() .slice(0, perMessageLimit); if (!content) continue; lines.push(`${role}: ${content}`); } return lines.join("\n").slice(0, totalLimit); } function compactAssistantModelMessageContent(content, maxLength = MODEL_CONTEXT_RECENT_MESSAGE_CHAR_LIMIT) { const text = normalizeMessageContent(content).replace(/\s+/g, " ").trim(); if (!text) return ""; if (text.length <= maxLength) return text; return `${text.slice(0, Math.max(120, maxLength - 3)).trim()}...`; } function buildAssistantModelConversationWindow(messages, options = {}) { const sourceMessages = (Array.isArray(messages) ? messages : []) .filter((entry) => entry && (entry.role === "user" || entry.role === "assistant")); if (!sourceMessages.length) { return { olderContextMessage: "", recentMessages: [], }; } const recentCount = Math.max(4, Number(options.recentCount) || MODEL_CONTEXT_RECENT_MESSAGE_LIMIT); const olderTranscriptCount = Math.max(4, Number(options.olderTranscriptCount) || MODEL_CONTEXT_OLDER_TRANSCRIPT_COUNT); const olderTranscriptTotalLimit = Math.max(400, Number(options.olderTranscriptTotalLimit) || MODEL_CONTEXT_OLDER_TRANSCRIPT_TOTAL_LIMIT); const recentMessagesSource = sourceMessages.slice(-recentCount); const olderMessagesSource = sourceMessages.slice(0, Math.max(0, sourceMessages.length - recentCount)); const olderTranscript = olderMessagesSource.length ? buildCarryForwardVisibleTranscript(olderMessagesSource, { count: Math.min(olderMessagesSource.length, olderTranscriptCount), perMessageLimit: 150, totalLimit: olderTranscriptTotalLimit, }) : ""; const recentMessages = recentMessagesSource .map((entry, index) => { const isLatest = index === recentMessagesSource.length - 1; const isNearLatest = index >= recentMessagesSource.length - 4; const maxLength = isLatest ? MODEL_CONTEXT_LATEST_MESSAGE_CHAR_LIMIT : (isNearLatest ? MODEL_CONTEXT_NEAR_MESSAGE_CHAR_LIMIT : MODEL_CONTEXT_RECENT_MESSAGE_CHAR_LIMIT); const content = compactAssistantModelMessageContent(entry.content, maxLength); if (!content) return null; return { role: entry.role, content, }; }) .filter(Boolean); return { olderContextMessage: olderTranscript ? `Earlier visible chat summary:\n${olderTranscript}\nUse it only when the latest messages omit a reference.` : "", recentMessages, }; } function looksLikeRestrictedAssistantFollowUp(message, conversationHistory = []) { const text = String(message || "").trim(); if (!text || text.length > 180) return false; const lower = text.toLowerCase(); if ( detectAssistantPowerAction(lower) || messageLooksLikeBusiestLookup(lower) || messageLooksLikeConsoleCheckRequest(lower) || !!detectDirectAccountFlowIntent(lower) ) { return false; } const lastAssistantText = getLastAssistantText(conversationHistory).toLowerCase(); if (!lastAssistantText) return false; const recentRestrictedResult = /\b(console|log|started|stopped|restarted|killed|busiest|highest|cpu|ram|memory|disk|storage|node|server|2fa|password|email|healthy|running|seconds?|uptime)\b/.test(lastAssistantText); if (!recentRestrictedResult) return false; const asksFollowUp = /[?]/.test(text) || /\b(so|and|what|why|how|how many|how much|which|did|does|is|was|are|were|okay|ok|then|mean|seconds?|sec|deci|bun|acum)\b/.test(lower); const refersToPreviousAnswer = /\b(it|that|those|them|this|seconds?|sec|started|crashed|running|healthy|console|logs?|cpu|ram|memory|disk|storage|node|server)\b/.test(lower); return asksFollowUp || refersToPreviousAnswer; } function messageLikelyNeedsAccessibleServerContext(message, conversationHistory = []) { const text = String(message || "").trim(); const lower = text.toLowerCase(); if (!lower) return false; if (extractAssistantServerCandidate(text)) return true; if (detectAssistantPowerAction(lower)) return true; if (messageLooksLikeBusiestLookup(lower)) return true; if (messageLooksLikeConsoleCheckRequest(lower)) return true; if (messageLooksLikeServerLimitsCheckRequest(lower)) return true; if (messageLooksLikeDiagnosisRequest(lower)) return true; const wantsNavigation = /\b(open|show|take me|go to|goto|navigate|bring me|launch|new tab|tab|pop ?up|manage|configure|config|edit|access)\b/.test(lower) && /\b(server|console|terminal|backups?|files?|activity|scheduler|tasks?|store|plugins?|versions?|resource(?:s| stats?)?|overview|info|details?|reinstall|settings?|preferences?|appearance|customization|account|security|databases?|nodes?|templates?|webhooks?|panel info|branding|background|captcha|maintenance|create user|create node|create template|pgadmin|mongodb|webhook)\b/.test(lower); if (wantsNavigation) return true; if (looksLikeRestrictedAssistantFollowUp(text, conversationHistory)) return true; if (messageLooksLikeServerInfoRequest(text)) return true; return /\b(server|servers|node|nodes|console|logs?|backups?|scheduler|activity|files?|resource(?:s| stats?)?|cpu|ram|memory|disk|storage|quota|limits?|template|templates|ip|address|port|ports|version)\b/i.test(text); } function normalizeShortReply(message) { return String(message || "") .toLowerCase() .replace(/[^a-z0-9]+/g, " ") .trim(); } function isAffirmativeShortReply(message) { const text = normalizeShortReply(message); return [ "yes", "yeah", "yep", "correct", "go ahead", "do it", "that works", "sounds good", "sure", "ok", "okay", "ok create it", "okay create it", "yes create it", "create it", "confirm", "confirmed", "use that", "use this", "use default", "use defaults", "default", "recommended", ].includes(text); } function assistantAskedProvisioningQuestion(conversationHistory = []) { const text = getLastAssistantText(conversationHistory).toLowerCase(); if (!text) return false; return ( /\b(which|what|how much|how many|choose|pick|tell me|do you want|would you like)\b/.test(text) && /\b(template|templates|node|nodes|server name|name|host port|port|ram|cpu|storage|defaults?)\b/.test(text) ); } function assistantAskedProvisioningConfirmation(conversationHistory = []) { const text = getLastAssistantText(conversationHistory).toLowerCase(); if (!text) return false; if (/\bi can create it now\b|\bi can create the server now\b|\bi can provision it now\b/.test(text)) { return true; } return ( /\b(ready|want me to|should i|go ahead|create it|create the server|apply it|use that|use this|confirm)\b/.test(text) && /\b(server|template|node|port|ram|cpu|storage|create|provision)\b/.test(text) ); } function assistantAskedDefaultsQuestion(conversationHistory = []) { const text = getLastAssistantText(conversationHistory).toLowerCase(); if (!text) return false; return /\bdefaults?\b/.test(text) && /\b(port|ram|cpu|storage)\b/.test(text); } function isCreateServerConversation(message, conversationHistory = []) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; const explicitCreateIntent = /\b(create|make|spin\s*up|deploy|provision)\b/.test(text) && /\b(server|minecraft|nodejs|python|discord|template|templates|node|nodes)\b/.test(text); if (explicitCreateIntent) return true; const shortProvisioningReply = text.length <= 120 && ( isAffirmativeShortReply(text) || /^\d{2,5}$/.test(text) || /\b\d+(?:\.\d+)?\s*(?:mb|gb|tb|cores?)\b/.test(text) || /\b(?:node|template|port|ram|cpu|storage|minecraft|paper|purpur|spigot|bukkit|fabric|forge|neoforge|python|nodejs)\b/.test(text) ); return (assistantAskedProvisioningQuestion(conversationHistory) || assistantAskedProvisioningConfirmation(conversationHistory)) && shortProvisioningReply; } // Multipart-header hygiene for the transcription upload: multer 2.4.0 decodes // %0D/%0A/%22 in the client's original filename back to CR/LF/quotes and npm // form-data (required at the top of this file) emits `filename="..."` with NO // escaping, so controls/quotes reaching the Groq part header can forge // multipart structure upstream of api.groq.com. Strip every ASCII control // char (NUL-0x1F plus 0x7F) outright and map `"` to `'` so tokens stay // visibly separated instead of vanishing; non-ASCII/Unicode filenames are // legitimate and pass through untouched. Idempotent by construction. function sanitizeTranscriptionFilename(filename) { return String(filename || "").replace(/[\x00-\x1F\x7F]/g, "").replace(/"/g, "'"); } function inferTranscriptionFilename(filename, mimeType) { // Sanitize BEFORE trimming so stripped edge controls can't leave leading/trailing space behind. const cleanName = sanitizeTranscriptionFilename(filename).trim(); if (cleanName) return cleanName; const mime = String(mimeType || "").toLowerCase(); if (mime.includes("wav")) return "dashboard-assistant.wav"; if (mime.includes("mp4") || mime.includes("m4a")) return "dashboard-assistant.m4a"; if (mime.includes("ogg")) return "dashboard-assistant.ogg"; if (mime.includes("mpeg") || mime.includes("mp3")) return "dashboard-assistant.mp3"; return "dashboard-assistant.webm"; } // Magic-byte sniffing for /transcribe uploads: the part's audio/* MIME is // client-asserted (multer can only read the header), so before any billable // STT call the assembled buffer must also open with a recognized audio // container signature. The allowlist covers everything the panel's own // client produces — EBML/WebM (MediaRecorder "audio/webm;codecs=opus"), // MP4/M4A ("audio/mp4") and RIFF/WAVE (the speech-fallback PCM WAV encoder) // — plus Ogg (Firefox's recorder default), FLAC and MP3 (ID3v2 tag or MPEG // audio frame sync). Buffers shorter than the longest signature read are // rejected: no real recording is that small. function sniffAudioSignature(buffer) { if (!Buffer.isBuffer(buffer) || buffer.length < 12) { return false; } if (buffer[0] === 0x1a && buffer[1] === 0x45 && buffer[2] === 0xdf && buffer[3] === 0xa3) { return true; // WebM/Matroska (EBML) } if (buffer.toString("latin1", 4, 8) === "ftyp") { return true; // MP4/M4A brand box } if (buffer.toString("latin1", 0, 4) === "RIFF" && buffer.toString("latin1", 8, 12) === "WAVE") { return true; // WAV/RIFF } const fourcc = buffer.toString("latin1", 0, 4); if (fourcc === "OggS" || fourcc === "fLaC") { return true; // Ogg / FLAC } if (buffer.toString("latin1", 0, 3) === "ID3") { return true; // MP3 with an ID3v2 tag } if (buffer[0] === 0xff && (buffer[1] & 0xe0) === 0xe0) { return true; // MP3/MPEG audio frame sync (0xFFEx; also covers ADTS AAC) } return false; } function isGenericAssistantReply(value) { const text = String(value || "").trim().toLowerCase(); return text === "" || text === "done." || text === "done" || text === "completed." || text === "completed"; } function buildReplyFromToolResult(toolName, toolResult) { const result = toolResult && typeof toolResult === "object" ? toolResult : null; if (!result) return ""; if (result.ok === false) { const error = String(result.error || "").trim(); const detail = String(result.detail || "").trim(); const candidates = Array.isArray(result.candidates) ? result.candidates.map((item) => String(item || "").trim()).filter(Boolean).slice(0, 5) : []; if (candidates.length && /server name is ambiguous|multiple servers matched|no accessible server matched/i.test(error)) { return `${error} Try ${candidates.join(", ")}.`; } if (detail && (!error || /^failed to create that server\.?$/i.test(error) || /^that action failed\.?$/i.test(error))) { return detail; } return error || detail || "That action failed."; } switch (String(toolName || "").trim()) { case "create_server": { const server = result.server && typeof result.server === "object" ? result.server : {}; const name = server.displayName || server.name || "the server"; const node = server.nodeName || server.nodeId || ""; return node ? `Created ${name} on ${node}.` : `Created ${name}.`; } case "install_plugin": { const pluginName = result.plugin?.name || result.plugin?.slug || "the plugin"; const serverName = result.server || "the server"; return `Installed ${pluginName} on ${serverName}.`; } case "request_delete_server": return result.server ? `Please confirm deletion for ${result.server}.` : "Please confirm that deletion first."; case "power_server": { if (result.resolutionRequired) { const action = result.action || "update"; if (action === "start") return "Finding the matching server to start."; if (action === "stop") return "Finding the matching server to stop."; if (action === "restart") return "Finding the matching server to restart."; if (action === "kill") return "Finding the matching server to kill."; return "Finding the matching server."; } const server = result.displayName || result.server || result.targets?.[0]?.displayName || result.targets?.[0]?.server || "the server"; const action = result.action || "updated"; if (action === "start") return `Requesting start for ${server}.`; if (action === "stop") return `Requesting stop for ${server}.`; if (action === "restart") return `Requesting restart for ${server}.`; if (action === "kill") return `Requesting kill for ${server}.`; return `Updated ${server}.`; } case "power_accessible_servers": { const count = Number(result.count) || (Array.isArray(result.servers) ? result.servers.length : 0) || (Array.isArray(result.targets) ? result.targets.length : 0); if (result.action === "start") return `Requesting start for ${count || "your"} accessible server${count === 1 ? "" : "s"}.`; if (result.action === "stop") return `Requesting stop for ${count || "your"} accessible server${count === 1 ? "" : "s"}.`; if (result.action === "restart") return `Requesting restart for ${count || "your"} accessible server${count === 1 ? "" : "s"}.`; if (result.action === "kill") return `Requesting kill for ${count || "your"} accessible server${count === 1 ? "" : "s"}.`; return "Running that power action now."; } case "open_server_page": { const section = formatAssistantServerPageSectionLabel(result.section); if (result.resolutionRequired) { return `Preparing a link to ${section}.`; } const server = result.displayName || result.server || "that server"; return section === "console" ? `Preparing a link to ${server}.` : `Preparing a link to ${section} for ${server}.`; } case "open_settings_destination": { const actionLabel = formatAssistantSettingsActionLabel(result.action); const panelLabel = formatAssistantSettingsPanelLabel(result.panel || inferAssistantSettingsPanelFromAction(result.action)); if (result.action) { return `Preparing a link to ${actionLabel}.`; } return `Preparing a link to ${panelLabel}.`; } case "get_busiest_node": if (result.metric === "cpu") return "Checking the busiest node by CPU now."; if (result.metric === "memory") return "Checking the busiest node by memory now."; if (result.metric === "disk") return "Checking the busiest node by disk now."; return "Checking the busiest node now."; case "get_busiest_server": if (result.metric === "cpu") return "Checking your busiest server by CPU now."; if (result.metric === "memory") return "Checking your busiest server by memory now."; if (result.metric === "disk") return "Checking your busiest server by disk now."; return "Checking your busiest server now."; case "check_server_console": return "Checking that server console now."; case "check_server_limits": return "Checking that server's limits now."; case "get_server_overview": return "Checking that server's details now."; case "diagnose_server": { const server = result.displayName || result.server || "that server"; return `Collecting diagnostics for ${server}.`; } case "update_minecraft_server_property": { const property = result.property || "that setting"; const count = Number(result.count) || (Array.isArray(result.targets) ? result.targets.length : 0); const restartText = result.restartAfter ? " with restart requested" : ""; return `Applying ${property} on ${count || "your"} Minecraft server${count === 1 ? "" : "s"}${restartText}.`; } case "list_files": { const server = result.server || "that server"; const path = result.path || "/"; const count = Array.isArray(result.entries) ? result.entries.length : 0; return `Found ${count} item${count === 1 ? "" : "s"} in ${path} on ${server}.`; } case "read_file": { const server = result.server || "that server"; const path = result.path || "that file"; return `Read ${path} on ${server}.`; } case "write_file": return result.path ? `Updated ${result.path} on ${result.server || "the server"}.` : "File updated."; case "create_directory": return result.path ? `Created ${result.path}.` : "Folder created."; case "rename_path": return result.destination ? `Moved to ${result.destination}.` : "Path renamed."; case "delete_path": return result.path ? `Deleted ${result.path}.` : "Path deleted."; case "open_account_flow": if (result.flow === "change_password") return "Opening password change."; if (result.flow === "change_email") return "Opening email change."; if (result.flow === "change_2fa") return "Opening 2FA settings."; if (result.flow === "recover_password") return "Opening password recovery."; if (result.flow === "recover_email") return "Opening email recovery."; if (result.flow === "recover_2fa") return "Opening 2FA recovery."; return "Opening that account flow."; default: return ""; } } function escapeRegex(value) { return String(value || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function shouldForceQueuedReply(toolName, toolResult) { if (!(toolResult && typeof toolResult === "object" && toolResult.browserActionQueued)) { return false; } return [ "get_busiest_node", "get_busiest_server", "check_server_console", "check_server_limits", "get_server_overview", "diagnose_server", "update_minecraft_server_property", ].includes(String(toolName || "").trim()); } // Tools whose browser action posts its own final AI-phrased reply. Suppressing the // queued "Checking..." chat message for these avoids duplicate assistant messages. const CLIENT_REPLYING_RESTRICTED_TOOLS = new Set([ "get_busiest_node", "get_busiest_server", "check_server_console", "check_server_limits", "get_server_overview", ]); function normalizeLooseText(value) { return String(value || "").toLowerCase().replace(/\s+/g, " ").trim(); } function parseAssistantToolArgs(value) { if (!value) return null; if (typeof value === "object") return value; if (typeof value !== "string") return null; try { return JSON.parse(value); } catch { return null; } } function isGenericServerPropertiesWriteToolCall(toolName, rawArgs) { if (String(toolName || "").trim() !== "write_file") return false; const parsedArgs = parseAssistantToolArgs(rawArgs); const path = String(parsedArgs?.path || "").trim().toLowerCase(); return path === "server.properties" || path.endsWith("/server.properties"); } function isWeakAssistantServerReference(value) { const clean = normalizeAssistantLookupText(value); if (!clean) return true; return /^(?:a|an|server|servers|a server|the server|that server|this server|serverul|serverele|srv|bot|instance|current|this|it|that|them|one|storage|disk|space|ram|memory|mem|cpu|usage|limits?|quota|quotas|headroom|resources?)$/i.test(clean); } function applyServerHintToToolArgs(toolName, rawArgs, serverHint = "") { const hint = String(serverHint || "").trim(); if (!hint) return rawArgs; const parsedArgs = parseAssistantToolArgs(rawArgs); if (!parsedArgs || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) { return rawArgs; } const name = String(toolName || "").trim(); const nextArgs = { ...parsedArgs }; let changed = false; const needsServerFallback = [ "power_server", "open_server_page", "check_server_console", "check_server_limits", "get_server_overview", "diagnose_server", "inspect_server", "list_files", "read_file", "write_file", "create_directory", "rename_path", "delete_path", "install_plugin", ].includes(name); if (needsServerFallback && isWeakAssistantServerReference(nextArgs.server)) { nextArgs.server = hint; changed = true; } if (name === "update_minecraft_server_property" && String(nextArgs.scope || "").trim().toLowerCase() !== "all_accessible_minecraft") { if (isWeakAssistantServerReference(nextArgs.server)) { nextArgs.server = hint; changed = true; } if (!String(nextArgs.scope || "").trim()) { nextArgs.scope = "single_server"; changed = true; } } if (!changed) return rawArgs; return typeof rawArgs === "string" ? JSON.stringify(nextArgs) : nextArgs; } function buildWriteThenPowerReply(writeResult, powerResult) { const writeReply = buildReplyFromToolResult("write_file", writeResult) || "File updated."; const powerReply = buildReplyFromToolResult("power_server", powerResult) || String(powerResult?.error || powerResult?.detail || "Power action failed.").trim(); return `${writeReply} ${powerReply}`.trim(); } function buildPowerOnlyCapabilityReply() { return "I can currently control servers, share direct links to server pages and admin settings tools, open account security popups, check live load, inspect a server console, check a server's RAM, CPU, and storage headroom, and report verified server details like template, node, IP, port, version, and backups."; } function buildInstantSmallTalkReply(message) { const text = String(message || "").trim(); const lower = text.toLowerCase(); if (!lower) return ""; if (/^(?:hey|hi|hello|yo|sup|what'?s up|good morning|good afternoon|good evening)(?:\s+(?:there|adpanel))?[!?.]*$/i.test(text)) { return "Hey."; } if (/^(?:thanks|thank you|ty|thx|nice|perfect|great|awesome)[!?.]*$/i.test(text)) { return "You're welcome."; } if (/^(?:how are you|are you there|you there|still there)[!?.]*$/i.test(text)) { return "I'm here."; } if (/^(?:what can you do|what do you do|help|help me|capabilities|what are your capabilities)[!?.]*$/i.test(text)) { return buildPowerOnlyCapabilityReply(); } return ""; } function buildRestrictedIntentSystemHint(intents = {}) { const hints = [ "Older chat may help resolve omitted references, but the latest explicit user request always wins.", ]; if (intents.directAccountFlow?.flow) { hints.push(`The latest user message is a clear account security request. Prefer calling open_account_flow with flow "${intents.directAccountFlow.flow}".`); } else if (intents.accountSecurityTopic) { hints.push("The latest user message is about account security (password, email, or 2FA). If the user wants to change or recover any of these, call open_account_flow with the matching flow instead of describing manual steps. Never claim a popup opened without calling the tool."); } if (intents.directBulkPowerFlow?.action) { hints.push(`The latest user message is a clear bulk power request. Prefer calling power_accessible_servers with action "${intents.directBulkPowerFlow.action}".`); } if (intents.directSinglePowerFlow?.args?.action) { hints.push(`The latest user message is a clear single-server power request. Prefer calling power_server with action "${intents.directSinglePowerFlow.args.action}" and the user's raw server wording.`); } if (intents.directLoadLookup?.toolName) { hints.push(`The latest user message is a clear live load lookup. Prefer calling ${intents.directLoadLookup.toolName}.`); } if (intents.directConsoleCheck?.args?.server) { hints.push("The latest user message is a clear live console request. Prefer calling check_server_console with the user's raw server wording."); } if (intents.directServerLimits?.args?.server) { hints.push("The latest user message is a clear per-server quota or limits request. Prefer calling check_server_limits with the user's raw server wording."); } if (intents.directServerInfo?.args?.server) { hints.push("The latest user message asks for verified server facts such as template, node, IP, port, version, or backups. Prefer calling get_server_overview. Never answer those facts from memory."); } if (intents.directOpenServerPage?.args?.server) { hints.push(`The latest user message is a clear server navigation request. Prefer calling open_server_page with section "${normalizeAssistantServerPageSection(intents.directOpenServerPage.args.section)}".`); } if (intents.directOpenSettings?.args?.panel || intents.directOpenSettings?.args?.action) { hints.push("The latest user message is a clear settings navigation request. Prefer calling open_settings_destination."); } return hints.join(" ").trim(); } function extractJsonObjectFromText(value) { const text = String(value || "").trim(); if (!text) return ""; const fencedMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/i); if (fencedMatch && fencedMatch[1]) { return String(fencedMatch[1]).trim(); } const firstBrace = text.indexOf("{"); const lastBrace = text.lastIndexOf("}"); if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) { return text.slice(firstBrace, lastBrace + 1).trim(); } return text; } function parseRestrictedAssistantPlan(rawContent) { const extracted = extractJsonObjectFromText(rawContent); if (!extracted) return null; try { const parsed = JSON.parse(extracted); return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null; } catch { return null; } } function normalizeRestrictedToolName(value) { const name = String(value || "").trim(); return [ "power_server", "power_accessible_servers", "open_server_page", "open_settings_destination", "open_account_flow", "get_busiest_node", "get_busiest_server", "check_server_console", "check_server_limits", "get_server_overview", ].includes(name) ? name : ""; } function sanitizeRestrictedToolArgs(toolName, rawArgs) { const parsed = rawArgs && typeof rawArgs === "object" && !Array.isArray(rawArgs) ? rawArgs : {}; if (toolName === "power_server") { const action = detectAssistantPowerAction(parsed.action); return { server: String(parsed.server || parsed.query || "").trim(), action: action || "", }; } if (toolName === "power_accessible_servers") { const action = detectAssistantPowerAction(parsed.action); return { action: action || "", }; } if (toolName === "open_server_page") { const server = String(parsed.server || parsed.query || "").trim(); const rawSection = [ parsed.section, parsed.destination, parsed.area, parsed.page, parsed.tab, ].find((value) => String(value || "").trim()); const nextArgs = {}; if (server) { nextArgs.server = server; } if (rawSection) { nextArgs.section = normalizeAssistantServerPageSection(rawSection); } return nextArgs; } if (toolName === "open_settings_destination") { const rawAction = [ parsed.action, parsed.modal, parsed.destination, parsed.popup, ].find((value) => String(value || "").trim()); const rawPanel = [ parsed.panel, parsed.section, parsed.category, parsed.destination, parsed.page, parsed.tab, ].find((value) => String(value || "").trim()); const action = normalizeAssistantSettingsAction(rawAction || ""); const panel = normalizeAssistantSettingsPanel(rawPanel || "") || (action ? inferAssistantSettingsPanelFromAction(action) : ""); const nextArgs = {}; if (panel) { nextArgs.panel = panel; } if (action) { nextArgs.action = action; } return nextArgs; } if (toolName === "open_account_flow") { const flow = String(parsed.flow || "").trim(); return { flow: [ "change_password", "change_email", "change_2fa", "recover_password", "recover_email", "recover_2fa", ].includes(flow) ? flow : "", }; } if (toolName === "get_busiest_node" || toolName === "get_busiest_server") { const metricDetails = inferAssistantMetricDetails([ parsed.metric, Array.isArray(parsed.includeMetrics) ? parsed.includeMetrics.join(" ") : parsed.includeMetrics, ].filter(Boolean).join(" ")); return { metric: metricDetails.metric, includeMetrics: metricDetails.includeMetrics, }; } if (toolName === "check_server_console") { return { server: String(parsed.server || parsed.query || "").trim(), question: String(parsed.question || "").trim(), }; } if (toolName === "check_server_limits") { const metricDetails = inferAssistantMetricDetails([ parsed.question, Array.isArray(parsed.includeMetrics) ? parsed.includeMetrics.join(" ") : parsed.includeMetrics, ].filter(Boolean).join(" ")); return { server: String(parsed.server || parsed.query || "").trim(), question: String(parsed.question || "").trim(), includeMetrics: metricDetails.includeMetrics, }; } if (toolName === "get_server_overview") { return { server: String(parsed.server || parsed.query || "").trim(), question: String(parsed.question || "").trim(), }; } return {}; } function hasMeaningfulRestrictedArgValue(value) { if (Array.isArray(value)) { return value.some((entry) => hasMeaningfulRestrictedArgValue(entry)); } if (value == null) { return false; } if (typeof value === "string") { return value.trim().length > 0; } if (typeof value === "object") { return Object.values(value).some((entry) => hasMeaningfulRestrictedArgValue(entry)); } return true; } function mergeRestrictedToolArgs(fallbackArgs, selectedArgs) { const fallback = fallbackArgs && typeof fallbackArgs === "object" && !Array.isArray(fallbackArgs) ? { ...fallbackArgs } : {}; const selected = selectedArgs && typeof selectedArgs === "object" && !Array.isArray(selectedArgs) ? selectedArgs : {}; for (const [key, value] of Object.entries(selected)) { if (!hasMeaningfulRestrictedArgValue(value)) { continue; } fallback[key] = value; } return fallback; } function buildRestrictedFallbackPlan({ trimmedMessage, directAccountFlow, directBulkPowerFlow, directSinglePowerFlow, directLoadLookup, directConsoleCheck, directServerLimits, directServerInfo, directOpenServerPage, directOpenSettings, }) { if (directAccountFlow) { return { reply: directAccountFlow.reply, toolName: "open_account_flow", toolArgs: { flow: directAccountFlow.flow }, }; } if (directBulkPowerFlow) { return { reply: "", toolName: "power_accessible_servers", toolArgs: { action: directBulkPowerFlow.action }, }; } if (directSinglePowerFlow) { return { reply: "", toolName: "power_server", toolArgs: directSinglePowerFlow.args, }; } if (directLoadLookup) { return { reply: "", toolName: directLoadLookup.toolName, toolArgs: directLoadLookup.args, }; } if (directConsoleCheck) { return { reply: "", toolName: "check_server_console", toolArgs: directConsoleCheck.args, }; } if (directServerLimits) { return { reply: "", toolName: "check_server_limits", toolArgs: directServerLimits.args, }; } if (directServerInfo) { return { reply: "", toolName: "get_server_overview", toolArgs: directServerInfo.args, }; } if (directOpenServerPage) { return { reply: "", toolName: "open_server_page", toolArgs: directOpenServerPage.args, }; } if (directOpenSettings) { return { reply: "", toolName: "open_settings_destination", toolArgs: directOpenSettings.args, }; } return { reply: "", toolName: "", toolArgs: {}, }; } async function buildRestrictedSingleShotPlan({ provider, apiKey, modelName, systemPrompt, latestUserMessage, inferredServerContextMessage, restrictedIntentSystemHint, conversationContextMessage, persistedMessages, requestChatCompletion, }) { const { olderContextMessage, recentMessages } = buildAssistantModelConversationWindow(persistedMessages, { recentCount: 16, olderTranscriptCount: 10, olderTranscriptTotalLimit: 1400, }); const response = await requestChatCompletion(provider, apiKey, { model: modelName, temperature: 0.1, max_tokens: 700, messages: [ { role: "system", content: systemPrompt }, { role: "system", content: [ "Return exactly one JSON object and nothing else.", 'Schema: {"reply":"short natural reply for the user","toolName":"power_server|power_accessible_servers|open_server_page|open_settings_destination|open_account_flow|get_busiest_node|get_busiest_server|check_server_console|check_server_limits|get_server_overview|","toolArgs":{}}', "Use an empty toolName when no tool is needed and answer directly in reply.", "If a tool is needed, keep reply short and queued-style, such as checking now or preparing a link now.", "Treat the latest user message as the main instruction. Older messages may only help resolve omitted references like it, that server, or short follow-up questions.", "If the latest message explicitly names a server, action, section, destination, popup, or panel, do not let older context override it.", "Do not claim the action is finished before the browser runs it.", "For navigation tools, never say the page was opened automatically. The dashboard will provide a clickable link the user can choose to open.", "For messy natural requests about startup time, crash cause, logs, whether a server started correctly, or whether it is running well, prefer check_server_console.", "For one named server questions about RAM, CPU, disk, storage, quotas, remaining space, or whether it is close to its limits, prefer check_server_limits.", "For questions about a server's facts such as its template, node, IP, address, port, version, fork, or backups, prefer get_server_overview. Never answer those facts from memory or invent them.", "For all accessible servers power requests, prefer power_accessible_servers.", "For one named server power requests, prefer power_server and pass the user's raw server wording in toolArgs.server.", "For requests to open, manage, configure, edit, or access a server page, console, backups, files, scheduler, activity, store, resource stats, or similar server areas, prefer open_server_page.", "For admin requests to open, manage, configure, edit, or access settings pages or settings modals such as nodes, appearance, branding, maintenance, captcha, databases, or webhooks, prefer open_settings_destination.", "For load questions, choose get_busiest_node or get_busiest_server and include any asked metrics.", "Use recent conversation context when the user refers to earlier answers.", "The latest explicit user request always overrides older context.", "Use older context only to resolve omitted references such as it, that, there, or the server we just discussed.", "If the latest user message explicitly names a server, destination, section, action, popup, or settings area, do not let older context replace it.", ].join(" "), }, ...(latestUserMessage ? [{ role: "system", // Belt and suspenders: completeChat already rejects over-limit input // before persistence, but this plan builder accepts raw text — keep // the system-role embedding bounded regardless of the caller. content: `Primary task: answer the latest user message exactly as requested: ${JSON.stringify(String(latestUserMessage || "").trim().slice(0, ASSISTANT_USER_MESSAGE_MAX_CHARS))}.`, }] : []), ...(inferredServerContextMessage ? [{ role: "system", content: inferredServerContextMessage }] : []), ...(restrictedIntentSystemHint ? [{ role: "system", content: restrictedIntentSystemHint }] : []), ...(conversationContextMessage ? [{ role: "system", content: conversationContextMessage }] : []), ...(olderContextMessage ? [{ role: "system", content: olderContextMessage }] : []), ...recentMessages, ], }); return response; } function coerceFiniteNumber(value) { const num = Number(value); return Number.isFinite(num) ? num : null; } function convertAmountToMb(amount, unit) { const numeric = coerceFiniteNumber(amount); const normalizedUnit = String(unit || "").trim().toLowerCase(); if (numeric == null) return null; if (normalizedUnit === "gb") return Math.round(numeric * 1024); if (normalizedUnit === "tb") return Math.round(numeric * 1024 * 1024); return Math.round(numeric); } function getRecentMessagesByRole(messages, role, limit = 14) { return (Array.isArray(messages) ? messages : []) .filter((entry) => String(entry?.role || "").toLowerCase() === String(role || "").toLowerCase()) .slice(-limit) .map((entry) => normalizeMessageContent(entry.content)) .filter(Boolean); } function findLatestRegexValue(texts, patterns, transform) { const list = Array.isArray(texts) ? texts : []; for (let index = list.length - 1; index >= 0; index -= 1) { const text = String(list[index] || ""); for (const pattern of patterns) { const match = pattern.exec(text); if (!match) continue; const result = typeof transform === "function" ? transform(match, text) : match[1]; if (result != null && result !== "") { return result; } } } return null; } function detectProvisioningDefaults(messages) { const recentMessages = Array.isArray(messages) ? messages : []; const userTexts = getRecentMessagesByRole(recentMessages, "user", 10); if (userTexts.some((text) => /\b(use|with|pick|choose|go with|take)\s+(the\s+)?defaults?\b/i.test(text))) { return true; } if (userTexts.some((text) => /\b(use|with|pick|choose|go with|take)\s+(the\s+)?recommended\b/i.test(text))) { return true; } if (userTexts.some((text) => /\bwhatever you recommend\b/i.test(text))) { return true; } const lastUserText = String(userTexts[userTexts.length - 1] || "").trim(); if (lastUserText && isAffirmativeShortReply(lastUserText) && assistantAskedDefaultsQuestion(recentMessages)) { return true; } return false; } function detectProvisioningNeedsResourcePrompt(messages) { const userTexts = getRecentMessagesByRole(messages, "user", 10); if (!userTexts.length) return false; const mentionedResources = userTexts.some((text) => /\b(limit(?:ed)?|resources?|ram|memory|cpu|storage|disk)\b/i.test(text)); const mentionedValues = userTexts.some((text) => /\b\d+(?:\.\d+)?\s*(?:mb|gb|tb|cores?)\b/i.test(text)); return mentionedResources && !mentionedValues; } function messageMentionsPluginInstall(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return false; return /\b(install|add|download|setup|set up)\b/.test(text) && /\b(plugin|plugins|modrinth|viaversion|geyser|luckperms|vault)\b/.test(text); } function resolveEntryByAliases(entries, requestedValue, aliasGetter) { const requested = String(requestedValue || "").trim().toLowerCase(); if (!requested) return null; const sourceEntries = Array.isArray(entries) ? entries : []; const exactMatch = sourceEntries.find((entry) => (typeof aliasGetter === "function" ? aliasGetter(entry) : []) .map((alias) => String(alias || "").trim().toLowerCase()) .includes(requested) ); if (exactMatch) return exactMatch; return sourceEntries.find((entry) => (typeof aliasGetter === "function" ? aliasGetter(entry) : []) .map((alias) => String(alias || "").trim().toLowerCase()) .some((alias) => alias.includes(requested) || requested.includes(alias)) ) || null; } function findAssistantSuggestedEntry(lastAssistantText, entries, aliasGetter) { const text = normalizeLooseText(lastAssistantText); if (!text) return null; const matches = []; for (const entry of Array.isArray(entries) ? entries : []) { const aliases = (typeof aliasGetter === "function" ? aliasGetter(entry) : []) .map((alias) => normalizeLooseText(alias)) .filter(Boolean) .sort((left, right) => right.length - left.length); if (!aliases.length) continue; const matched = aliases.some((alias) => { const pattern = new RegExp(`(^|[^a-z0-9])${escapeRegex(alias)}(?=$|[^a-z0-9])`, "i"); return pattern.test(text); }); if (matched) matches.push(entry); } return matches.length === 1 ? matches[0] : null; } function formatChoiceList(values, limit = 3) { const items = Array.from(new Set((Array.isArray(values) ? values : []).map((value) => String(value || "").trim()).filter(Boolean))).slice(0, limit); if (!items.length) return ""; if (items.length === 1) return items[0]; if (items.length === 2) return `${items[0]} or ${items[1]}`; return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`; } function isVagueProvisioningReply(message) { const text = String(message || "").trim().toLowerCase(); if (!text) return true; if (/\b(which|what|how much|how many|choose|pick|tell me)\b/.test(text) && /\b(template|node|name|host port|port|ram|cpu|storage|defaults?)\b/.test(text)) { return false; } if (text.split(/\s+/).filter(Boolean).length <= 4 && !/\b(template|node|name|host port|port|ram|cpu|storage|created|defaults?)\b/.test(text)) { return true; } return /\b(i need|need one more detail|need more detail|need more information|need to know more|tell me more)\b/.test(text); } function findLatestAliasEntry(texts, entries, aliasGetter) { const sourceTexts = Array.isArray(texts) ? texts : []; const sourceEntries = Array.isArray(entries) ? entries : []; const preparedEntries = sourceEntries .map((entry) => { const aliases = (typeof aliasGetter === "function" ? aliasGetter(entry) : []) .map((alias) => String(alias || "").trim()) .filter(Boolean) .sort((left, right) => right.length - left.length); return { entry, aliases }; }) .filter((item) => item.aliases.length > 0); for (let textIndex = sourceTexts.length - 1; textIndex >= 0; textIndex -= 1) { const text = normalizeLooseText(sourceTexts[textIndex]); for (const item of preparedEntries) { for (const alias of item.aliases) { const aliasText = normalizeLooseText(alias); if (!aliasText) continue; const pattern = new RegExp(`(^|[^a-z0-9])${escapeRegex(aliasText)}(?=$|[^a-z0-9])`, "i"); if (pattern.test(text)) { return item.entry; } } } } return null; } function parseCarryForwardProvisioningContext(texts) { const sourceTexts = Array.isArray(texts) ? texts : []; const carryText = sourceTexts .slice() .reverse() .find((text) => /\bcarry-forward provisioning context:/i.test(String(text || ""))); if (!carryText) { return {}; } const readField = (name) => { const match = new RegExp(`\\b${escapeRegex(name)}=([^;]+)`, "i").exec(String(carryText || "")); return match ? String(match[1] || "").trim() : ""; }; const readIntField = (name) => { const raw = readField(name); const parsed = parseInt(raw, 10); return Number.isInteger(parsed) ? parsed : null; }; const readFloatField = (name) => { const raw = readField(name); const parsed = parseFloat(raw); return Number.isFinite(parsed) ? parsed : null; }; const nodeValue = readField("node"); return { templateId: readField("template") || null, templateName: readField("template") || null, nodeId: nodeValue || null, nodeName: nodeValue || null, serverName: readField("serverName") || null, mcFork: readField("mcFork") || null, mcVersion: readField("mcVersion") || null, hostPort: readIntField("hostPort"), ramMb: readIntField("ramMb"), cpuCores: readFloatField("cpuCores"), storageMb: readIntField("storageMb"), useDefaults: /^true$/i.test(readField("useDefaults")), wantsResourcePrompt: /^true$/i.test(readField("wantsResourcePrompt")), }; } // Shared response sink for both provider https.request helpers: the body is // accumulated as utf8 — setEncoding("utf8") never splits a multibyte // sequence across chunks, so per-chunk Buffer.byteLength is exact — and the // connection is destroyed once the total crosses // ASSISTANT_PROVIDER_RESPONSE_MAX_BYTES, rejecting with the fixed generic // message below (it must keep falling through the router's inferStatusCode // to 500, so no classifier keyword). `settled` makes the promise settle // exactly once: req.destroy() makes the torn-down response emit a late // "error" (ECONNRESET), which is swallowed here rather than surfacing as an // uncaught event on res; the callers' req.on("error", reject) then no-ops. // adpanel:http-straggler — deliberate raw https.request dials (NOT // services/node-http.js's core): fixed AI-provider hosts, reject-based // contract with classified provider errors, per-provider TLS agents and // multipart (groq) bodies the core cannot express; posture here already // covers the core's crash class (response error listener, body cap, // single-settle, timeout). function collectProviderResponse(req, res, resolve, reject) { let data = ""; let bytes = 0; let settled = false; res.setEncoding("utf8"); res.on("data", (chunk) => { if (settled) return; bytes += Buffer.byteLength(chunk); if (bytes > ASSISTANT_PROVIDER_RESPONSE_MAX_BYTES) { settled = true; reject(new Error("The AI provider response was rejected because it was bigger than the accepted size.")); req.destroy(); return; } data += chunk; }); res.on("end", () => { if (settled) return; settled = true; try { resolve({ status: res.statusCode || 0, data: data ? JSON.parse(data) : {}, }); } catch { resolve({ status: res.statusCode || 0, data: { raw: data }, }); } }); // Premature socket tears (server abort, or the cap destroy above) land on // res as ECONNRESET; reject like the callers' req.on("error") does so the // promise cannot hang until timeout, guarded against double-settle. res.on("error", (err) => { if (settled) return; settled = true; reject(err); }); } function jsonApiRequest(fullUrl, { method = "POST", headers = {}, body = null, timeoutMs = 60_000, timeoutMessage = "Request timeout", agent = null } = {}) { return new Promise((resolve, reject) => { const payload = body == null ? null : (typeof body === "string" ? body : JSON.stringify(body || {})); const url = new URL(fullUrl); const req = https.request( { hostname: url.hostname, port: Number(url.port) || 443, path: `${url.pathname}${url.search}`, method, headers: Object.assign({}, headers, payload == null ? {} : { "Content-Length": Buffer.byteLength(payload), }), agent: agent || undefined, servername: url.hostname || undefined, timeout: timeoutMs, }, (res) => collectProviderResponse(req, res, resolve, reject), ); req.on("error", reject); req.on("timeout", () => req.destroy(new Error(timeoutMessage))); if (payload != null) { req.write(payload); } req.end(); }); } function groqMultipartRequest(pathname, apiKey, formData, timeoutMs = 60_000) { return new Promise((resolve, reject) => { const headers = formData.getHeaders({ "Authorization": `Bearer ${apiKey}`, }); const req = https.request( { hostname: "api.groq.com", port: 443, path: pathname, method: "POST", headers, agent: ASSISTANT_PROVIDER_HTTPS_AGENTS.groq, servername: "api.groq.com", timeout: timeoutMs, }, (res) => collectProviderResponse(req, res, resolve, reject), ); req.on("error", reject); req.on("timeout", () => req.destroy(new Error("Groq request timeout"))); formData.pipe(req); }); } // Provider HTTP failures (non-200 from the chat/transcription endpoints): the // raw provider body may embed model lists, org ids, quota/configuration // details or internal endpoints, and the router forwards every non-500 error // message to the client verbatim (respondWithError). So the raw detail is // classified HERE, server-side only, and the thrown message is one fixed // generic string per class. Each message deliberately keeps the exact keyword // the router's status classifier keys on ("rate limit"/"quota" -> 429, // "could not be found" -> 404, "invalid" -> 400), so client-visible HTTP // statuses are unchanged. The provider detail itself never leaves the server: // it is logged single-line (control characters stripped so a hostile body // cannot forge log lines, truncated) — response bodies never contain the API // key, which travels only in request headers. function describeProviderError(providerName, status, detail) { const rawText = typeof detail === "string" ? detail : (() => { try { return detail == null ? "" : JSON.stringify(detail); } catch { return ""; } })(); const text = rawText.toLowerCase(); let errorClass; if (/rate limit|rate_limit|too many requests/.test(text)) { errorClass = "rateLimited"; } else if (/quota|exhausted|billing|insufficient/.test(text)) { errorClass = "quotaExhausted"; } else if (status === 429) { errorClass = "rateLimited"; } else if (status === 401 || status === 403 || /api[ _-]?key|unauthorized|forbidden|permission denied|invalid_api_key|authentication|credential/.test(text)) { errorClass = "badCredentials"; } else if (/not found|could not be found|does not exist|no such model/.test(text)) { errorClass = "modelNotFound"; } else if (status === 400) { errorClass = "invalidRequest"; } else { errorClass = "unavailable"; } const logDetail = rawText.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, 600) || `status ${status}`; console.error(`[dashboard-assistant] ${providerName} request failed (status ${status}, class ${errorClass}): ${logDetail}`); switch (errorClass) { case "rateLimited": return "The AI provider is rate limited right now. Please try again in a few minutes."; case "quotaExhausted": return "The AI provider quota is used up for now. Please try again later."; case "badCredentials": return "The configured AI provider rejected the stored credentials as invalid. Check the panel settings."; case "modelNotFound": return "The selected AI model could not be found. Pick another model in the panel."; case "invalidRequest": return "The AI provider rejected the request as invalid. Please try again shortly."; default: return "The AI provider request failed. Please try again later."; } } // Per-user serialization for the assistant chat check-and-rotate decisions // (getActiveChat) and the empty-chat reuse/prune decision (resetChat). Two // concurrent turns for the same user used to both observe the // MAX_CHAT_MESSAGES boundary, each create a fresh chat (duplicate chats, // split history), and race the old chat's deletion — a third in-flight turn // could then insert into the already-deleted chat and FK-fail (500) after the // provider call had already been paid for. Only the short DB check-and-act // section runs under the lock; provider calls never do, so a turn cannot // hold it long enough to starve the user's other turns. Entries are dropped // once settled, so the map stays bounded. const chatRotationLocks = new Map(); function runSerializedPerUser(userEmail, fn) { const key = String(userEmail || "").trim().toLowerCase(); const previous = chatRotationLocks.get(key) || Promise.resolve(); // Chain regardless of the predecessor's outcome: a failed turn must never // wedge the user's later turns. The returned promise still rejects to the // caller as usual; only the chained tail swallows the outcome. const result = previous.then(fn, fn); const release = () => { if (chatRotationLocks.get(key) === tail) chatRotationLocks.delete(key); }; const tail = result.then(release, release); chatRotationLocks.set(key, tail); return result; } function createDashboardAssistantService(deps) { if (!deps || typeof deps !== "object") { throw new Error("Dashboard assistant dependencies are required."); } // Off the boot path: re-wrap legacy provider API keys into enc-v2 under // the dedicated secret — both enc-v1 values and enc-v2 values the // deprecated SESSION_SECRET mint fallback produced — and, once .env holds // no enc-v1 values, drop SECRET_KEY from the enc-v1 decryption chain for // this process. index.js has already auto-provisioned the dedicated secret // into .env/process.env by the time this fires. The first attempt keeps // the historical fire-and-forget setImmediate shape; if it ends with // retirement unconfirmed, scheduleAssistantProviderSecretMigration keeps // re-running the migration in this process with backoff (30s → 2min → // 10min → 30min…) and one secret-free console.error per retry, instead of // silently staying in the weak legacy state until the next boot. Requests // that decrypt before setImmediate fires at worst still see SECRET_KEY as // a candidate for a few extra ticks. scheduleAssistantProviderSecretMigration(deps); // Single runner for every tool execution (chat loop, forced power chains, // direct flows), so the power-only allowlist is decided once here at // construction instead of being re-derived per call site. const runTool = createDashboardAssistantToolRunner(deps, { allowedToolNames: POWER_ONLY_ASSISTANT ? POWER_TOOL_NAMES : null, }); const history = createDashboardAssistantHistory({ ...deps, title: DEFAULT_CHAT_TITLE }); // Keep decrypted provider keys in memory so chat requests avoid repeated // .env reads and crypto work. The cache is NOT load-once: the panel runs // several pm2 cluster workers sharing one filesystem, and an admin can // rotate a key on any of them. Every .env writer replaces the file // atomically (tmp+fsync+rename), so the rename bumps the file's mtime on // the shared fs — that mtime is the cross-worker invalidation signal // checked on every use below, with a hard TTL as the safety net. const providerSecretCache = { loaded: false, loadedAt: 0, // mtime seen for the .env this cache was built from; -1 means the file // was not statable/existing at load time. null means "unknown" (dep // unavailable) and disables the mtime check until the next full load. envMtimeMs: null, providerPreference: "", keys: { groq: "", google: "", }, encrypted: { groq: "", google: "", }, // Envelope version ("enc-v1"/"enc-v2") of each provider's stored // encrypted value, "" when nothing is stored encrypted. Drives the // fail-closed legacy guard below: an "enc-v1" entry means the value still // decrypts through the weak legacy chain (unsalted SHA-256 KDF, and // SECRET_KEY — a secret a third party holds — while retirement is // unconfirmed), so chats must refuse to exercise it. envelopeVersions: { groq: "", google: "", }, // Occupancy of each provider's ORPHANED_V1 quarantine slot in the read // .env: true when a recovery artifact (a persistently-undecryptable // enc-v1 value the migration moved out of its live slot) sits there. // Observability only — surfaced to admins as keyMigration.orphanedKeys; // no runtime path ever reads the slot's value. orphanedV1: { groq: false, google: false, }, modelOverrides: { groq: "", google: "", }, }; // Returns the current .env mtime as a comparable number, -1 when the file // is gone, or null when it cannot be determined (dep missing or throwing — // callers then fall back to the TTL-only path). Must never throw. function readEnvFileMtimeMs() { if (typeof deps.getEnvFileMtimeMs !== "function") return null; try { const mtimeMs = deps.getEnvFileMtimeMs(); return typeof mtimeMs === "number" && Number.isFinite(mtimeMs) ? mtimeMs : null; } catch { return null; } } function loadProviderSecretCache() { // Stat BEFORE reading: a write that lands between the stat and the read // leaves the recorded mtime older than the file's, so the next use sees a // mismatch and reloads again (a spurious reload). Statting after the read // could record a just-rotated key as already-seen while the // cache still holds the revoked one — the unsafe direction. const mtimeAtLoad = readEnvFileMtimeMs(); const env = typeof deps.readEnvFile === "function" ? deps.readEnvFile() : {}; const nextKeys = { groq: "", google: "" }; const nextEncrypted = { groq: "", google: "" }; const nextEnvelopeVersions = { groq: "", google: "" }; const nextOrphanedV1 = { groq: false, google: false }; for (const providerId of Object.keys(PROVIDER_LABELS)) { const secretConfig = getAssistantProviderSecretConfig(providerId); if (!secretConfig) continue; // Quarantine-slot occupancy (same env read order as everything else): // refreshed at this single full-reload point. A save never creates or // removes orphan slots — only the migration's verified quarantine write // (or a manual operator edit) does — so the in-place saveProviderToken // mirror deliberately does not touch this field; a real occupancy // change always bumps the .env mtime and lands on the next reload. const orphanKey = ASSISTANT_PROVIDER_SECRET_ORPHANED_V1_ENV_KEYS[providerId] || ""; nextOrphanedV1[providerId] = !!sanitizeToken(env[orphanKey] || process.env[orphanKey] || ""); const encryptedValue = sanitizeToken( env[secretConfig.encrypted] || process.env[secretConfig.encrypted] || "" ); let resolvedKey = ""; if (encryptedValue) { try { resolvedKey = decryptAssistantProviderToken(encryptedValue); } catch (error) { console.error(`[dashboard-assistant] Failed to decrypt ${providerId} API key:`, error); } } if (!resolvedKey) { for (const legacyEnvKey of secretConfig.legacy) { resolvedKey = sanitizeToken(env[legacyEnvKey] || process.env[legacyEnvKey] || ""); if (resolvedKey) break; } } nextKeys[providerId] = resolvedKey; nextEncrypted[providerId] = encryptedValue; // Track WHAT KIND of envelope the stored value wears, independent of // whether it decrypted: an undecryptable enc-v1 value still reports // "enc-v1" here, but its resolved key is "" so the legacy guard's // resolvable-key requirement keeps it on the pre-existing " // is not configured" path. A value falling back to the legacy // PLAINTEXT env keys (no encrypted value at all) stays "" — plaintext // at rest is a pre-existing hygiene issue, out of the guard's scope. nextEnvelopeVersions[providerId] = assistantProviderEnvelopeVersion(encryptedValue); } providerSecretCache.providerPreference = sanitizeProvider( env.DASHBOARD_ASSISTANT_PROVIDER || process.env.DASHBOARD_ASSISTANT_PROVIDER || "" ); providerSecretCache.keys = nextKeys; providerSecretCache.encrypted = nextEncrypted; providerSecretCache.envelopeVersions = nextEnvelopeVersions; providerSecretCache.orphanedV1 = nextOrphanedV1; providerSecretCache.modelOverrides = { groq: sanitizeToken(env.DASHBOARD_ASSISTANT_GROQ_MODEL || process.env.DASHBOARD_ASSISTANT_GROQ_MODEL || ""), google: sanitizeToken(env.DASHBOARD_ASSISTANT_GOOGLE_MODEL || process.env.DASHBOARD_ASSISTANT_GOOGLE_MODEL || ""), }; // Recorded only once the whole load succeeded: a throw above leaves the // previous cache state untouched, so the next use retries (loaded=false, // or the TTL check fires again on an already-loaded cache). providerSecretCache.envMtimeMs = mtimeAtLoad; providerSecretCache.loadedAt = Date.now(); providerSecretCache.loaded = true; return providerSecretCache; } function ensureProviderSecretCache() { if (!providerSecretCache.loaded) return loadProviderSecretCache(); // Hard safety net: force a reload even when the mtime gate below sees no // change, so a missed/quirky mtime can never pin a revoked key for long. if (Date.now() - providerSecretCache.loadedAt >= PROVIDER_SECRET_CACHE_REVALIDATE_TTL_MS) { return loadProviderSecretCache(); } // Cross-worker invalidation: another pm2 sibling may have rotated a key // (its write ended in an atomic rename, bumping the shared .env's mtime). // A mismatch — including the file vanishing (-1) — means this cache is // stale and must be rebuilt from the file. No dep (null) falls back to // the TTL above alone. const currentMtimeMs = readEnvFileMtimeMs(); if (currentMtimeMs !== null && currentMtimeMs !== providerSecretCache.envMtimeMs) { return loadProviderSecretCache(); } return providerSecretCache; } function getGoogleKey() { return sanitizeToken(ensureProviderSecretCache().keys.google || ""); } function getGroqKey() { return sanitizeToken(ensureProviderSecretCache().keys.groq || ""); } function getStoredProviderPreference() { return sanitizeProvider(ensureProviderSecretCache().providerPreference || ""); } function getProviderKey(provider) { if (provider === "google") return getGoogleKey(); if (provider === "groq") return getGroqKey(); return ""; } // DELIBERATE no-fallback: a stored provider preference whose key is still // enc-v1 (guard-blocked) hard-fails the chat even when the other provider // is healthy — this is the intended fail-closed forcing function (it // self-heals via the retry scheduler, and admins see keyMigration.legacyPending), // so future readers must not "fix" it silently in either direction. function getResolvedProvider() { const preferred = getStoredProviderPreference(); if (preferred && getProviderKey(preferred)) { return preferred; } if (getGroqKey()) return "groq"; if (getGoogleKey()) return "google"; return preferred || "groq"; } // Envelope version of the provider's STORED encrypted value as seen by the // current cache generation: "enc-v1", "enc-v2", or "" (nothing stored // encrypted — including the legacy plaintext fallback, deliberately). Reads // through ensureProviderSecretCache so a rotated .env (mtime bump) or the // TTL safety net refreshes the version alongside the keys themselves. function getStoredEnvelopeVersion(provider) { const providerId = sanitizeProvider(provider); if (!providerId) return ""; const versions = ensureProviderSecretCache().envelopeVersions || {}; return String(versions[providerId] || ""); } // Server-side visibility for the fail-closed legacy guard below: ONE // secret-free console.error per provider per 10 minutes, keyed by provider // id. Scoped to this service instance so a hot-reload/reconstruction (and // every fresh test service) starts a fresh window instead of inheriting a // silence that outlives the code that earned it. Never log key material. const legacyKeyGuardLastLoggedAt = new Map(); const LEGACY_KEY_GUARD_LOG_INTERVAL_MS = 10 * 60 * 1000; // Fail-closed chokepoint for every path that is about to SEND a provider // key to the provider's API. While a stored enc-v1 envelope remains, the // key is protected only by the weak legacy chain, and that chain has two // weaknesses at once: the enc-v1 KDF is an UNsalted, unstretched SHA-256 // (trivially brute-forced offline once the secret material is suspected), // and — until the migration confirms retirement — one of its candidates is // SECRET_KEY, the shared reCAPTCHA secret that a third party (Google) holds // by design. The startup migration re-wraps enc-v1 → enc-v2 (scrypt, // per-value salt, dedicated secret only) and then drops SECRET_KEY from the // chain; while that has been ATTEMPTED but not CONFIRMED, the known-weak // state persists, so chats must refuse to exercise the legacy-protected key // instead of silently sending it out (defense beyond the migration's own // in-process retries). Deliberately NOT applied inside getProviderKey: the // models-list endpoint, bootstrap and other read paths keep working — only // paths that put the key on the wire are guarded. function assertAssistantProviderKeyMigrated(provider) { const providerId = sanitizeProvider(provider); if (!providerId) return; const migrationState = getAssistantProviderSecretMigrationState(); // Boot window: the first migration attempt fires via setImmediate right // after service construction. Until it has run, retirement is merely // UNCONFIRMED, not failed — those few ticks keep today's permissive // behavior so startup requests are not spuriously refused (the migration // may still retire .env mid-flight and any later request re-evaluates). // Once retirement IS confirmed, .env holds no enc-v1 values and // SECRET_KEY is already dropped from the chain — nothing left to guard, // for the rest of the process. if (migrationState.retired || !migrationState.attempted) return; // Only an actually-stored enc-v1 envelope fires the guard. A re-saved // (enc-v2) key clears the condition for its provider on the next cache // load; an undecryptable enc-v1 value resolves to no key at all and is // handled by the pre-existing " is not configured" path. if (getStoredEnvelopeVersion(providerId) !== ASSISTANT_PROVIDER_SECRET_VERSION) return; // Fire only when the weak-chain value would actually be exercised: the // provider must currently have a resolvable non-empty key. Without this // the guard would double-error over a value that already fails upstream. const apiKey = getProviderKey(providerId); if (!apiKey) return; // Rate-limited operator visibility (see legacyKeyGuardLastLoggedAt): the // thrown error surfaces per chat attempt to the user, but the server log // stays quiet for 10 minutes per provider. const now = Date.now(); const lastLoggedAt = legacyKeyGuardLastLoggedAt.get(providerId) || 0; if (now - lastLoggedAt >= LEGACY_KEY_GUARD_LOG_INTERVAL_MS) { legacyKeyGuardLastLoggedAt.set(providerId, now); console.error( `[dashboard-assistant] blocked request: ${providerId} key still uses the legacy enc-v1 envelope (weak legacy chain active); awaiting migration/re-save` ); } // The marker "legacy encryption envelope" is load-bearing: // routes/dashboard-assistant.js classifies this error as a curated 503 // (admin guidance on the settings surface) instead of a generic 500. // Secret-free by construction: the message names the envelope state and // the two practical remediations, never key material. throw new Error( `The stored ${getProviderLabel(providerId)} API key still uses the legacy encryption envelope and its automatic re-encryption has not completed. ` + "The legacy envelope relies on a weak legacy key derivation, so the key stays exposed until it is re-encrypted. " + "Re-save the provider key in the assistant settings to migrate it, or restore .env write access and restart the panel." ); } function getChatModelForProvider(provider) { return provider === "google" ? DEFAULT_GOOGLE_MODEL : DEFAULT_GROQ_MODEL; } function getTranscriptionModelForProvider(provider) { return provider === "google" ? DEFAULT_GOOGLE_TRANSCRIPTION_MODEL : DEFAULT_GROQ_TRANSCRIPTION_MODEL; } // Live chat-model discovery, cached briefly so a burst of messages does not // turn into a burst of model-list requests. Chat model ids are resolved // against the provider's current list so a provider-side lineup change // degrades to a different valid model instead of failing every request. const providerModelListCache = { groq: { ids: [], fetchedAt: 0, inFlight: null }, google: { ids: [], fetchedAt: 0, inFlight: null }, }; async function getLiveChatModelIds(provider) { const entry = providerModelListCache[provider]; if (!entry) return []; const cacheTtl = entry.ids.length ? PROVIDER_MODELS_CACHE_TTL_MS : PROVIDER_MODELS_ERROR_TTL_MS; if (Date.now() - entry.fetchedAt < cacheTtl) return entry.ids; if (entry.inFlight) return entry.inFlight; const apiKey = getProviderKey(provider); if (!apiKey) return entry.ids; entry.inFlight = (async () => { try { const ids = await fetchProviderChatModelIds(provider, apiKey); if (ids.length) entry.ids = ids; entry.fetchedAt = Date.now(); return entry.ids; } catch (error) { // Keep serving the last known list; retry after the short error TTL. entry.fetchedAt = Date.now(); console.warn(`[dashboard-assistant] failed to refresh ${provider} model list:`, error?.message); return entry.ids; } finally { entry.inFlight = null; } })(); return entry.inFlight; } function sanitizeRequestedChatModel(requestedModel) { const value = String(requestedModel ?? "").trim(); if (!value || value.length > REQUESTED_MODEL_MAX_LENGTH) return ""; return REQUESTED_MODEL_PATTERN.test(value) ? value : ""; } async function resolveChatModelForProvider(provider, requestedModel) { const cleanProvider = sanitizeProvider(provider) || "groq"; const override = (ensureProviderSecretCache().modelOverrides || {})[cleanProvider] || ""; if (override) return override; try { const liveIds = await getLiveChatModelIds(cleanProvider); // The live list is the allowlist: an empty list (fetch failure, no key) // honors nothing, so a client pick can never bypass it. const candidate = sanitizeRequestedChatModel(requestedModel); if (candidate && liveIds.includes(candidate)) return candidate; const preferred = (CHAT_MODEL_PREFERENCES[cleanProvider] || []).find((id) => liveIds.includes(id)); if (preferred) return preferred; if (liveIds.length) return liveIds[0]; } catch (error) { console.warn(`[dashboard-assistant] chat model resolution failed for ${cleanProvider}:`, error?.message); } return getChatModelForProvider(cleanProvider); } async function loadAccessibleServersForAssistant(userEmail) { const normalizedEmail = String(userEmail || "").trim().toLowerCase(); const cachedEntry = accessibleServersForAssistantCache.get(normalizedEmail); if (cachedEntry && Date.now() - cachedEntry.updatedAt < ACCESSIBLE_SERVERS_CACHE_TTL_MS) { return cachedEntry.list; } const list = ((typeof deps.loadServersIndex === "function" ? await deps.loadServersIndex() : []) || []).filter(Boolean); const user = typeof deps.findUserByEmail === "function" ? await deps.findUserByEmail(normalizedEmail) : null; let resolvedList = list; if (!user?.admin) { const accessList = ((typeof deps.getAccessListForEmail === "function" ? await deps.getAccessListForEmail(normalizedEmail) : []) || []) .map((item) => String(item || "").trim().toLowerCase()) .filter(Boolean); const loweredAccess = new Set(accessList); resolvedList = loweredAccess.has("all") ? list : list.filter((entry) => entry?.name && loweredAccess.has(String(entry.name).trim().toLowerCase())); } accessibleServersForAssistantCache.set(normalizedEmail, { updatedAt: Date.now(), list: resolvedList, }); return resolvedList; } const { ensureTables, getPrimaryChat, createFreshChat, getChatById, getChatMessages, getChatMessageCount, addMessage, deleteChat } = history; async function resetChat(userEmail) { return runSerializedPerUser(userEmail, () => history.resetChat(userEmail)); } // A turn's message inserts run outside the per-user rotation lock, so the // chat getActiveChat resolved can be rotated away (FK cascade-deleted) by a // concurrent turn — cross-process workers share no lock — before the insert // lands. The insert then fails on ER_NO_REFERENCED_ROW_2 and the route 500s // even though the provider call was already paid for. Recovery path for // those inserts is layered: original chat → primary chat (the rotation's // fresh chat, so the payload lands in the user's current conversation — // which the rotation left with a carry-forward summary, keeping context // coherent) → a brand-new chat → one last-resort insert into another fresh // chat created that tick if the resolved chat died before the insert // landed. Every hop re-checks its target before retrying, so the insert // stays at-most-once: an attempt that may have committed (its chat still // exists) is rethrown instead of duplicated, and only a definitively // uncommitted one (its chat is gone — a committed row could not have // outlived it) moves down the ladder; a chat deleted after a committed // insert still cascades the row (accepted loss no retry could prevent). // Returns the chat the payload actually landed in; ok=false means it was // re-homed. async function rehomeAssistantMessage(userEmail, originalChatId, messagePayload) { const originalChat = await getChatById(userEmail, originalChatId); if (originalChat) { try { await addMessage(originalChat.id, messagePayload); return { chat: originalChat, ok: true }; } catch (error) { // The chat can still vanish between the existence check and the // insert (rotation won that race); fall through and re-resolve — // but only when it is really gone. A still-live chat means the // insert failed for another reason (possibly after committing), // and retrying would write the payload a second time. if (await getChatById(userEmail, originalChatId)) { throw error; } } } let liveChat = (await getChatById(userEmail, originalChatId)) || (await getPrimaryChat(userEmail)) || (await createFreshChat(userEmail)); if (!liveChat) { // getPrimaryChat and createFreshChat insert then SELECT their own row, // so a prune racing between those statements makes them return falsy. // One more insert is the last roll; a DB that still cannot echo its own // insert is a genuine fault and propagating it is correct. liveChat = await createFreshChat(userEmail); } if (!liveChat) { throw new Error("dashboard-assistant: could not resolve a live chat to re-home the assistant reply"); } try { await addMessage(liveChat.id, messagePayload); } catch (error) { // Same at-most-once rule as the original-chat attempt: retry only when // the failing insert definitively did not commit, which a vanished // target chat guarantees (a committed row could not have outlived it). // A still-live chat may already hold the payload — the trailing // updated_at write can fail after COMMIT — so rethrow instead. if (await getChatById(userEmail, liveChat.id)) { throw error; } // Last resort: a chat created this tick is empty but younger than any // concurrent prune's snapshot, so that prune cannot target it this tick. // If even this insert fails, the original error is the honest one. const lastResortChat = await createFreshChat(userEmail); try { await addMessage(lastResortChat.id, messagePayload); } catch { throw error; } return { chat: lastResortChat, ok: false }; } return { chat: liveChat, ok: false }; } async function getActiveChat(userEmail, requestedChatId = null) { // Resolve + count + rotate is check-then-act on this user's chat rows, so // it runs under the per-user lock (see runSerializedPerUser): a turn never // gets a chat id a lock-ordered rotation is about to delete, and a waiter // re-reads the fresh chat a predecessor just rotated to instead of // rotating again. The lock ends here — the provider call and the message // inserts that follow stay outside it, so a turn already resolved when a // cross-worker rotation deletes its chat self-heals via // rehomeAssistantMessage instead of FK-failing after a paid provider call. return runSerializedPerUser(userEmail, async () => { const requestedChat = requestedChatId ? await getChatById(userEmail, requestedChatId) : null; const chat = requestedChat || await getPrimaryChat(userEmail); if (!chat) return null; const messageCount = await getChatMessageCount(chat.id); if (messageCount < MAX_CHAT_MESSAGES) { return chat; } const previousMessages = await getChatMessages(chat.id, CHAT_HISTORY_LIMIT); const freshChat = await createFreshChat(userEmail); const carryForwardSummary = await buildCarryForwardSystemSummary(previousMessages); if (carryForwardSummary) { await addMessage(freshChat.id, { role: "system", content: carryForwardSummary, model: "adpanel-chat-handoff", }); } if (chat.id !== freshChat.id) { await deleteChat(userEmail, chat.id).catch(() => {}); } return freshChat; }); } async function inferProvisioningContext(messages) { const userTexts = getRecentMessagesByRole(messages, "user", 16); const assistantTexts = getRecentMessagesByRole(messages, "assistant", 12); const systemTexts = getRecentMessagesByRole(messages, "system", 6); const carryForwardContext = parseCarryForwardProvisioningContext(systemTexts); if (!userTexts.length && !assistantTexts.length && !Object.keys(carryForwardContext).length) return null; const provisioningThreadLikely = userTexts.some((text) => /\b(create|make|spin up|deploy|provision|new server|server)\b/i.test(text)) || assistantTexts.some((text) => /\b(template|node|server name|host port|port|ram|cpu|storage|create)\b/i.test(text)) || Object.keys(carryForwardContext).length > 0; if (!provisioningThreadLikely) return null; let templates = []; let nodes = []; try { templates = typeof deps.loadTemplatesFile === "function" ? (deps.loadTemplatesFile() || []) : []; } catch { templates = []; } try { nodes = typeof deps.loadNodes === "function" ? await deps.loadNodes() || [] : []; } catch { nodes = []; } const lastUserText = String(userTexts[userTexts.length - 1] || "").trim(); const lastAssistantText = String(assistantTexts[assistantTexts.length - 1] || "").trim().toLowerCase(); const acceptedAssistantSuggestion = isAffirmativeShortReply(lastUserText); const impliedMinecraft = userTexts.some((text) => /\b(minecraft|paper|purpur|spigot|bukkit|vanilla)\b/i.test(text)); const impliedNodeJs = userTexts.some((text) => /\b(node\.?js|nodejs|discord bot|discord-bot)\b/i.test(text)); const impliedPython = userTexts.some((text) => /\bpython\b/i.test(text)); const template = findLatestAliasEntry(userTexts, templates, (entry) => [entry?.id, entry?.name]); const node = findLatestAliasEntry(userTexts, nodes, (entry) => [entry?.name, entry?.id, entry?.uuid]); const assistantSuggestedTemplate = acceptedAssistantSuggestion ? findAssistantSuggestedEntry(lastAssistantText, templates, (entry) => [entry?.id, entry?.name]) : null; const assistantSuggestedNode = acceptedAssistantSuggestion ? findAssistantSuggestedEntry(lastAssistantText, nodes, (entry) => [entry?.name, entry?.id, entry?.uuid]) : null; const hostPort = findLatestRegexValue( userTexts, [ /\b(?:host\s+port|hostport|port)\s*(?:is\s+|to\s+|=)?(\d{1,5})\b/i, /\b(?:on|using)\s+port\s+(\d{1,5})\b/i, /\buse\s+(\d{1,5})\b/i, /^(\d{2,5})$/i, ], (match) => { const port = parseInt(match[1], 10); return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : null; } ); const ramMb = findLatestRegexValue( userTexts, [ /\b(?:ram|memory)\s*(?:is\s+|to\s+|=)?(\d+(?:\.\d+)?)\s*(mb|gb|tb)\b/i, /\b(\d+(?:\.\d+)?)\s*(mb|gb|tb)\s*(?:of\s+)?(?:ram|memory)\b/i, ], (match) => convertAmountToMb(match[1], match[2]) ); const cpuCores = findLatestRegexValue( userTexts, [ /\b(?:cpu|cores?)\s*(?:is\s+|to\s+|=)?(\d+(?:\.\d+)?)\b/i, /\b(\d+(?:\.\d+)?)\s*(?:cpu\s*cores?|cores?)\b/i, ], (match) => coerceFiniteNumber(match[1]) ); const storageMb = findLatestRegexValue( userTexts, [ /\b(?:storage|disk)\s*(?:is\s+|to\s+|=)?(\d+(?:\.\d+)?)\s*(mb|gb|tb)\b/i, /\b(\d+(?:\.\d+)?)\s*(mb|gb|tb)\s*(?:of\s+)?(?:storage|disk)\b/i, ], (match) => convertAmountToMb(match[1], match[2]) ); const serverName = findLatestRegexValue( userTexts, [ /\b(?:name(?:\s+it|\s+is)?|call\s+it|server\s+name(?:\s+is)?|create\s+(?:it\s+)?as)\s+["']?([a-z0-9._-]{2,48})["']?\b/i, /\b(?:named|called)\s+["']?([a-z0-9._-]{2,48})["']?\b/i, ], (match) => match[1] ); const mcFork = findLatestRegexValue( userTexts, [ /\b(paper|pufferfish|purpur|spigot|bukkit|vanilla)\b/i, ], (match) => String(match[1] || "").trim().toLowerCase() ); const mcVersion = findLatestRegexValue( userTexts, [ /\b(?:minecraft\s+)?(1\.\d{1,2}(?:\.\d{1,2})?)\b/i, ], (match) => String(match[1] || "").trim() ); const context = { templateId: template?.id || assistantSuggestedTemplate?.id || carryForwardContext.templateId || (impliedMinecraft ? "minecraft" : (impliedNodeJs ? "nodejs" : (impliedPython ? "python" : null))), templateName: template?.name || template?.id || assistantSuggestedTemplate?.name || assistantSuggestedTemplate?.id || carryForwardContext.templateName || null, nodeId: node?.id || node?.uuid || node?.name || assistantSuggestedNode?.id || assistantSuggestedNode?.uuid || assistantSuggestedNode?.name || carryForwardContext.nodeId || null, nodeName: node?.name || node?.id || node?.uuid || assistantSuggestedNode?.name || assistantSuggestedNode?.id || assistantSuggestedNode?.uuid || carryForwardContext.nodeName || null, hostPort: hostPort ?? carryForwardContext.hostPort, ramMb: ramMb ?? carryForwardContext.ramMb, cpuCores: cpuCores ?? carryForwardContext.cpuCores, storageMb: storageMb ?? carryForwardContext.storageMb, serverName: serverName || carryForwardContext.serverName || null, mcFork: mcFork === "vanilla" ? "paper" : (mcFork || carryForwardContext.mcFork || null), mcVersion: mcVersion || carryForwardContext.mcVersion || null, useDefaults: detectProvisioningDefaults(messages) || !!carryForwardContext.useDefaults, wantsResourcePrompt: detectProvisioningNeedsResourcePrompt(messages) || !!carryForwardContext.wantsResourcePrompt, }; if (!context.templateId && /\btemplate\b/.test(lastAssistantText) && lastUserText) { context.templateId = lastUserText; } if (!context.nodeId && /\bnode\b/.test(lastAssistantText) && lastUserText && !isAffirmativeShortReply(lastUserText)) { context.nodeId = lastUserText; } if (!context.serverName && /\bserver name\b|\bname the server\b|\bname should i use\b/.test(lastAssistantText) && lastUserText && !isAffirmativeShortReply(lastUserText)) { context.serverName = lastUserText; } if (context.hostPort == null && /\bport\b/.test(lastAssistantText) && /^\d{2,5}$/.test(lastUserText)) { const parsedPort = parseInt(lastUserText, 10); if (Number.isInteger(parsedPort) && parsedPort >= 1 && parsedPort <= 65535) { context.hostPort = parsedPort; } } if (context.hostPort == null && acceptedAssistantSuggestion && /\bport\b/.test(lastAssistantText)) { const defaultPortMatch = /\bdefault(?: is|:)?\s*(\d{2,5})\b/i.exec(lastAssistantText); if (defaultPortMatch) { const parsedPort = parseInt(defaultPortMatch[1], 10); if (Number.isInteger(parsedPort) && parsedPort >= 1 && parsedPort <= 65535) { context.hostPort = parsedPort; } } } if (context.ramMb == null && /\bram|memory\b/.test(lastAssistantText)) { const ramMatch = /\b(\d+(?:\.\d+)?)\s*(mb|gb|tb)\b/i.exec(lastUserText); if (ramMatch) context.ramMb = convertAmountToMb(ramMatch[1], ramMatch[2]); } if (context.cpuCores == null && /\bcpu|cores?\b/.test(lastAssistantText)) { const cpuMatch = /\b(\d+(?:\.\d+)?)\s*(?:cpu\s*cores?|cores?)\b/i.exec(lastUserText) || /^(\d+(?:\.\d+)?)$/i.exec(lastUserText); if (cpuMatch) context.cpuCores = coerceFiniteNumber(cpuMatch[1]); } if (context.storageMb == null && /\bstorage|disk\b/.test(lastAssistantText)) { const storageMatch = /\b(\d+(?:\.\d+)?)\s*(mb|gb|tb)\b/i.exec(lastUserText); if (storageMatch) context.storageMb = convertAmountToMb(storageMatch[1], storageMatch[2]); } return Object.values(context).some((value) => value != null && value !== "") ? context : null; } async function buildCarryForwardSystemSummary(messages) { const recentMessages = (Array.isArray(messages) ? messages : []) .filter((entry) => entry && (entry.role === "user" || entry.role === "assistant")) .slice(-24); if (!recentMessages.length) { return ""; } const parts = []; const provisioningContext = await inferProvisioningContext(recentMessages); const provisioningSummary = buildConversationContextMessage(provisioningContext); if (provisioningSummary) { parts.push(provisioningSummary.replace(/^Recent inferred provisioning context:/, "Carry-forward provisioning context:")); } const lastAssistantText = getLastAssistantText(recentMessages); if (lastAssistantText && (assistantAskedProvisioningQuestion(recentMessages) || assistantAskedProvisioningConfirmation(recentMessages))) { parts.push(`Carry-forward last assistant prompt: ${lastAssistantText}`); } const recentUserTexts = getRecentMessagesByRole(recentMessages, "user", 5); if (recentUserTexts.length) { parts.push(`Carry-forward recent user intent: ${recentUserTexts.join(" | ").slice(0, 700)}`); } const visibleTranscript = buildCarryForwardVisibleTranscript(recentMessages, { count: 18, perMessageLimit: 180, totalLimit: 2600, }); if (visibleTranscript) { parts.push(`Carry-forward visible chat transcript:\n${visibleTranscript}`); } return parts.join("\n\n").trim().slice(0, 4200); } function buildConversationContextMessage(context) { if (!context) return ""; const parts = []; if (context.templateId || context.templateName) { parts.push(`template=${context.templateId || context.templateName}`); } if (context.nodeName || context.nodeId) { parts.push(`node=${context.nodeName || context.nodeId}`); } if (context.serverName) { parts.push(`serverName=${context.serverName}`); } if (context.mcFork) { parts.push(`mcFork=${context.mcFork}`); } if (context.mcVersion) { parts.push(`mcVersion=${context.mcVersion}`); } if (context.hostPort != null) { parts.push(`hostPort=${context.hostPort}`); } if (context.ramMb != null) { parts.push(`ramMb=${context.ramMb}`); } if (context.cpuCores != null) { parts.push(`cpuCores=${context.cpuCores}`); } if (context.storageMb != null) { parts.push(`storageMb=${context.storageMb}`); } if (context.useDefaults) { parts.push("useDefaults=true"); } if (context.wantsResourcePrompt) { parts.push("wantsResourcePrompt=true"); } if (!parts.length) return ""; return `Recent inferred provisioning context: ${parts.join("; ")}. Reuse these values unless the user changes them. Ask only for missing or ambiguous fields.`; } async function buildProvisioningPlan(messages) { const context = await inferProvisioningContext(messages); if (!context) return null; let templates = []; let nodes = []; try { templates = typeof deps.loadTemplatesFile === "function" ? (deps.loadTemplatesFile() || []) : []; } catch { templates = []; } try { nodes = typeof deps.loadNodes === "function" ? await deps.loadNodes() || [] : []; } catch { nodes = []; } const template = resolveEntryByAliases(templates, context.templateId || context.templateName, (entry) => [entry?.id, entry?.name]); const node = resolveEntryByAliases(nodes, context.nodeId || context.nodeName, (entry) => [entry?.id, entry?.uuid, entry?.name]); const useDefaults = !!context.useDefaults; const templateDefaultPort = template?.defaultPort != null ? parseInt(template.defaultPort, 10) || null : null; const missingFields = []; if (!template) missingFields.push("template"); if (!node) missingFields.push("node"); if (!context.serverName) missingFields.push("name"); if (context.hostPort == null && !(useDefaults && templateDefaultPort != null)) { missingFields.push("port"); } const createArgs = { name: context.serverName || "", displayName: context.serverName || "", templateId: template?.id || context.templateId || "", nodeId: node?.id || node?.uuid || node?.name || context.nodeId || "", hostPort: context.hostPort != null ? context.hostPort : templateDefaultPort, mcFork: context.mcFork || undefined, mcVersion: context.mcVersion || undefined, resources: Object.assign( {}, context.ramMb != null ? { ramMb: context.ramMb } : {}, context.cpuCores != null ? { cpuCores: context.cpuCores } : {}, context.storageMb != null ? { storageMb: context.storageMb } : {} ), }; if (!Object.keys(createArgs.resources).length) { delete createArgs.resources; } return { context, template, node, useDefaults, wantsResourcePrompt: !!context.wantsResourcePrompt, templateDefaultPort, missingFields, createArgs, templateChoices: templates.slice(0, 3).map((entry) => entry?.name || entry?.id).filter(Boolean), nodeChoices: nodes.filter((entry) => entry?.online !== false).slice(0, 3).map((entry) => entry?.name || entry?.id || entry?.uuid).filter(Boolean), }; } function buildProvisioningFollowUp(plan) { if (!plan) { return "Which detail should I use to create the server?"; } const missing = Array.isArray(plan.missingFields) ? plan.missingFields : []; if (!missing.length) { return "I can create it now."; } const initialProvisioningPrompt = missing.includes("template") && missing.includes("node") && missing.includes("name") && missing.includes("port"); if (initialProvisioningPrompt) { return "Tell me the template, node, server name, and port. If you want limits, add RAM, CPU, and storage too."; } const missingCore = missing.filter((field) => ["template", "node", "name", "port"].includes(field)); if (missingCore.length > 1) { const labels = missingCore.map((field) => { if (field === "template") return "template"; if (field === "node") return "node"; if (field === "name") return "server name"; return "port"; }); return `Tell me the ${formatChoiceList(labels, 4)}.`; } if (missing.includes("template")) { const choices = formatChoiceList(plan.templateChoices); return choices ? `Which template should I use: ${choices}?` : "Which template should I use?"; } if (missing.includes("node")) { const choices = formatChoiceList(plan.nodeChoices); return choices ? `Which node should I use: ${choices}?` : "Which node should I use?"; } if (missing.includes("name")) { return "What should I name the server?"; } if (missing.includes("port")) { return plan.templateDefaultPort != null ? `Which port should I use? The default is ${plan.templateDefaultPort}.` : "Which port should I use?"; } if (plan.wantsResourcePrompt) { return "If you want limits, tell me the RAM, CPU, or storage."; } return "Which detail should I use to create the server?"; } async function maybeRunProvisioningFallback({ userEmail, userIp, trimmedMessage, persistedMessages, clientActions }) { if (!isCreateServerConversation(trimmedMessage, persistedMessages)) { return null; } const plan = await buildProvisioningPlan(persistedMessages); if (!plan) { return null; } if (plan.missingFields.length > 0) { return { reply: buildProvisioningFollowUp(plan), model: "adpanel-provisioning-router", toolName: "", toolResult: null, }; } if (plan.wantsResourcePrompt && !plan.createArgs.resources) { return { reply: "If you want limits, tell me the RAM, CPU, or storage.", model: "adpanel-provisioning-router", toolName: "", toolResult: null, }; } const toolResult = await runTool({ name: "create_server", args: plan.createArgs, userEmail, userIp, clientActions, }); return { reply: buildReplyFromToolResult("create_server", toolResult) || String(toolResult?.error || toolResult?.detail || "That server could not be created.").trim(), model: "adpanel-provisioning-router", toolName: "create_server", toolResult, }; } const maybeUpdateChatTitle = history.maybeUpdateChatTitle; async function saveProviderToken({ provider, token }) { // Strict allowlist: an unknown or missing provider id is a validation // failure, never a silent fall-back to the groq slot — the old // `|| "groq"` fallback let a key meant for another provider overwrite a // working Groq credential in its own slot while reporting ok:true. const resolvedProvider = sanitizeProvider(provider); if (!resolvedProvider) { throw new Error("Please select a valid AI provider."); } const providerLabel = getProviderLabel(resolvedProvider); const providerSecretConfig = getAssistantProviderSecretConfig(resolvedProvider); if (!providerSecretConfig) { throw new Error(`Unsupported provider: ${resolvedProvider}`); } const cachedSecrets = ensureProviderSecretCache(); const existingKey = getProviderKey(resolvedProvider); const existingEncryptedValue = sanitizeToken(cachedSecrets.encrypted[resolvedProvider] || ""); // Empty/missing token means "activate this provider and keep its stored // key" (the settings UI sends "" while the field shows the stored mask). // Anything else is a new key and must pass full validation before any // storage write happens. const sanitized = token == null || String(token).trim() === "" ? "" : validateProviderApiToken(token, providerLabel); if (!sanitized && !existingKey) { throw new Error(`Please enter a valid ${providerLabel} API key.`); } const updates = { DASHBOARD_ASSISTANT_PROVIDER: resolvedProvider }; const tokenToPersist = sanitized || (!existingEncryptedValue ? existingKey : ""); const encryptedToken = tokenToPersist ? encryptAssistantProviderToken(tokenToPersist) : ""; if (encryptedToken) { updates[providerSecretConfig.encrypted] = encryptedToken; // At-rest hygiene: only when a fresh envelope was minted THIS call (and // rides in this same batch), purge the provider's legacy plaintext .env // keys so no plaintext copy lingers on disk. Round-trip-verify first — // on any mismatch (or decrypt failure), skip the purge silently and // still save exactly as before (an unverified purge could destroy the // only usable copy). The purge rides in the SAME atomic batch as the // encrypted write, so there is never a window where the plaintext is // gone but the encrypted save failed. An empty-token save with an // existing encrypted value mints no envelope and must not purge // anything; a plaintext-only empty-token save re-wraps the stored // plaintext, and that minted envelope is round-trip verified before the // purge rides the same atomic batch. let legacyPurgeVerified = false; try { legacyPurgeVerified = decryptAssistantProviderToken(encryptedToken) === tokenToPersist; } catch { legacyPurgeVerified = false; } if (legacyPurgeVerified) { for (const legacyEnvKey of providerSecretConfig.legacyPurgeable || []) { updates[legacyEnvKey] = null; } } // Legacy process.env values are deliberately left untouched: the // /api/ai/keys feature's runtime semantics and this assistant's // plaintext fallback stay unchanged — at-rest hygiene is about the file. } const saved = deps.writeEnvFileBatch(updates); if (!saved) { throw new Error(`Failed to save the ${providerLabel} API key.`); } process.env.DASHBOARD_ASSISTANT_PROVIDER = resolvedProvider; if (encryptedToken) { process.env[providerSecretConfig.encrypted] = encryptedToken; } const effectiveKey = sanitized || existingKey; cachedSecrets.providerPreference = resolvedProvider; cachedSecrets.keys[resolvedProvider] = effectiveKey; if (encryptedToken) { cachedSecrets.encrypted[resolvedProvider] = encryptedToken; // Keep the in-place mirror complete: the keys/encrypted slots above are // updated without a reload, so the envelope version must move with // them. A fresh envelope is always enc-v2 (minted under the dedicated // secret), which clears the fail-closed legacy guard for this provider // immediately — even before the .env mtime bump triggers the next // ensureProviderSecretCache reload. cachedSecrets.envelopeVersions[resolvedProvider] = assistantProviderEnvelopeVersion(encryptedToken); } cachedSecrets.loaded = true; return { provider: resolvedProvider, label: providerLabel, configured: !!effectiveKey, obscuredValue: buildStoredKeyFieldValue(effectiveKey), }; } async function transcribeWithGroq(apiKey, { buffer, mimeType, filename, language, prompt }) { const formData = new FormData(); formData.append("file", buffer, { // Defense in depth: sanitizeTranscriptionFilename is idempotent, so // double-applying after inferTranscriptionFilename is a no-op — but it // keeps a future caller passing a raw client filename from injecting // into the multipart part header. filename: sanitizeTranscriptionFilename(inferTranscriptionFilename(filename, mimeType)), contentType: mimeType || "audio/webm", }); formData.append("model", DEFAULT_GROQ_TRANSCRIPTION_MODEL); formData.append("response_format", "json"); formData.append("temperature", "0"); const safeLanguage = sanitizeTranscriptionLanguage(language); if (safeLanguage) { formData.append("language", safeLanguage); } const safePrompt = sanitizeTranscriptionPrompt(prompt); if (safePrompt) { formData.append("prompt", safePrompt); } const response = await groqMultipartRequest("/openai/v1/audio/transcriptions", apiKey, formData, 90_000); if (response.status !== 200) { throw new Error(describeProviderError( "Groq", response.status, response.data?.error?.message || response.data?.error || response.data?.raw )); } const transcript = String(response.data?.text || "").trim(); if (!transcript) { throw new Error("The recording could not be transcribed."); } return { transcript, model: DEFAULT_GROQ_TRANSCRIPTION_MODEL, }; } async function transcribeWithGoogle(apiKey, { buffer, mimeType, language, prompt }) { // safeLanguage is sanitized before prompt interpolation; the raw value is client-controlled. const safeLanguage = sanitizeTranscriptionLanguage(language); const safePrompt = sanitizeTranscriptionPrompt(prompt) || "Transcribe this audio literally and accurately. Keep technical product words intact and prefer numeric digits."; const textPrompt = safeLanguage ? `${safePrompt} The audio's spoken language is ${safeLanguage}; transcribe it verbatim in that language.` : safePrompt; const requestBody = { model: DEFAULT_GOOGLE_TRANSCRIPTION_MODEL, input: [ { type: "text", text: textPrompt }, { type: "audio", data: buffer.toString("base64"), mime_type: mimeType || "audio/webm", }, ], }; const response = await jsonApiRequest(GOOGLE_INTERACTIONS_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey, }, body: requestBody, agent: ASSISTANT_PROVIDER_HTTPS_AGENTS.google, timeoutMs: 90_000, timeoutMessage: "Google AI Studio request timeout", }); if (response.status !== 200) { throw new Error(describeProviderError( "Google AI Studio", response.status, response.data?.error?.message || response.data?.error || response.data?.raw )); } const outputs = Array.isArray(response.data?.outputs) ? response.data.outputs : []; const transcript = String(outputs[outputs.length - 1]?.text || response.data?.output?.text || "").trim(); if (!transcript) { throw new Error("The recording could not be transcribed."); } return { transcript, model: DEFAULT_GOOGLE_TRANSCRIPTION_MODEL, }; } async function transcribeAudio({ buffer, mimeType, filename, language, prompt }) { const provider = getResolvedProvider(); const apiKey = getProviderKey(provider); if (!apiKey) { throw new Error(`${getProviderLabel(provider)} is not configured.`); } // Fail-closed legacy guard: the resolved key is about to be sent to the // provider's transcription endpoint, so refuse while it still wears the // weak enc-v1 envelope and retirement is unconfirmed. A no-op before the // first migration attempt (boot window) and after confirmed retirement. assertAssistantProviderKeyMigrated(provider); if (!Buffer.isBuffer(buffer) || buffer.length === 0) { throw new Error("No audio data was received."); } if (buffer.length > AUDIO_UPLOAD_LIMIT_BYTES) { throw new Error("The audio recording is too large."); } // The audio/* part header is client-asserted (honor-system), so gate the // billable provider call on the buffer's real magic bytes too. The // rejection message stays generic — buffer contents are never reflected // to the client, only the detected signature is logged server-side. const declaredType = String(mimeType || "").trim().toLowerCase(); if (!declaredType.startsWith("audio/") || !sniffAudioSignature(buffer)) { const head = buffer.subarray(0, 12).toString("hex"); const loggedType = declaredType.replace(/[^a-z0-9.+\/;=-]/g, "").slice(0, 80) || "unknown"; console.warn(`[dashboard-assistant] transcription upload rejected: no recognized audio signature (declared ${loggedType}, first bytes ${head})`); throw new Error("The uploaded audio format is not supported."); } if (provider === "google") { return transcribeWithGoogle(apiKey, { buffer, mimeType, filename, language, prompt }); } return transcribeWithGroq(apiKey, { buffer, mimeType, filename, language, prompt }); } async function requestChatCompletion(provider, apiKey, payload) { if (provider === "google") { return jsonApiRequest(GOOGLE_OPENAI_CHAT_URL, { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, "Content-Type": "application/json", }, body: Object.assign({ reasoning_effort: "low" }, payload), agent: ASSISTANT_PROVIDER_HTTPS_AGENTS.google, timeoutMs: 90_000, timeoutMessage: "Google AI Studio request timeout", }); } // Groq counts reasoning tokens against max_tokens, so gpt-oss models // would burn the small reply budgets before emitting any visible text. const groqPayload = /gpt-oss/i.test(String(payload?.model || "")) ? Object.assign({ reasoning_effort: "low" }, payload) : payload; return jsonApiRequest("https://api.groq.com/openai/v1/chat/completions", { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, "Content-Type": "application/json", }, body: groqPayload, agent: ASSISTANT_PROVIDER_HTTPS_AGENTS.groq, timeoutMs: 90_000, timeoutMessage: "Groq request timeout", }); } function mergeContinuationText(base, continuation) { const first = String(base || "").trim(); const second = String(continuation || "").trim(); if (!first) return second; if (!second) return first; if (first === second) return first; if (second.toLowerCase().startsWith(first.toLowerCase())) return second; if (first.toLowerCase().endsWith(second.toLowerCase())) return first; const needsSpace = /[a-z0-9)]$/i.test(first) && /^[a-z0-9(]/i.test(second); return `${first}${needsSpace ? " " : ""}${second}`.trim(); } async function continueTruncatedReply({ provider, apiKey, modelName, modelMessages, partialContent }) { const response = await requestChatCompletion(provider, apiKey, { model: modelName, temperature: 0.1, max_tokens: 600, messages: [ ...modelMessages, { role: "assistant", content: partialContent }, { role: "user", content: "Continue from exactly where you stopped. Do not restart or repeat. Finish the answer in one short complete reply.", }, ], }); if (response.status !== 200) { return partialContent; } const continuation = normalizeMessageContent(response.data?.choices?.[0]?.message?.content); return mergeContinuationText(partialContent, continuation); } async function summarizeDirectAssistantToolResult({ provider, apiKey, userMessage, toolName, toolResult, requestedModel }) { const modelName = await resolveChatModelForProvider(provider, requestedModel); const compactResult = toolName === "read_file" ? { server: toolResult?.server || null, path: toolResult?.path || null, truncated: !!toolResult?.truncated, originalLength: toolResult?.originalLength ?? null, content: String(toolResult?.content || "").slice(0, 5000), } : { server: toolResult?.server || null, path: toolResult?.path || null, entries: Array.isArray(toolResult?.entries) ? toolResult.entries.slice(0, 80) : [], }; const response = await requestChatCompletion(provider, apiKey, { model: modelName, temperature: 0.1, max_tokens: 700, messages: [ { role: "system", content: [ "You are ADPanel Assistant.", "Always reply in English.", "Keep replies short and useful for speech.", "Use only the tool result you were given.", "If the user asked what to change, point to the most relevant setting or issue briefly.", "If the user asked to see a file, summarize the important parts instead of dumping the whole file.", "If the tool listed a directory, mention the most relevant entries only.", ].join(" "), }, { role: "user", content: `User request: ${userMessage}\n\nTool used: ${toolName}\nTool result JSON:\n${JSON.stringify(compactResult)}`, }, ], }); if (response.status !== 200) { return buildReplyFromToolResult(toolName, toolResult) || "I checked it."; } const summary = normalizeMessageContent(response.data?.choices?.[0]?.message?.content); return summary || buildReplyFromToolResult(toolName, toolResult) || "I checked it."; } async function completeLightweightAssistantChat({ provider, apiKey, userEmail, chat, trimmedMessage, persistedMessages, requestedModel, }) { // Fail-closed legacy guard. The sole caller (executeAssistantConversation) // already asserts on the key it resolved, but this function owns the first // provider-bound call (model resolution can hit the provider's model-list // endpoint with the key), so it re-asserts on its own inputs — the cache // may have reloaded in between and the chokepoint stays in one place per // entry point. No-op before the first migration attempt and after // confirmed retirement. assertAssistantProviderKeyMigrated(provider); const modelName = await resolveChatModelForProvider(provider, requestedModel); const { olderContextMessage, recentMessages } = buildAssistantModelConversationWindow(persistedMessages, { recentCount: 10, olderTranscriptCount: 6, olderTranscriptTotalLimit: 900, }); const startedAt = Date.now(); const response = await requestChatCompletion(provider, apiKey, { model: modelName, temperature: 0.2, max_tokens: 700, messages: [ { role: "system", content: buildSystemPrompt({ appName: "ADPanel", userEmail, powerOnly: true }), }, ...(olderContextMessage ? [{ role: "system", content: olderContextMessage }] : []), ...recentMessages, ], }); const thinkingTimeMs = Date.now() - startedAt; if (response.status !== 200) { throw new Error(describeProviderError( getProviderLabel(provider), response.status, response.data?.error?.message || response.data?.error || response.data?.raw )); } const reply = normalizeMessageContent(response.data?.choices?.[0]?.message?.content) || "How can I help?"; // The provider call above ran outside the per-user rotation lock, so the // chat may have been rotated away mid-call; re-home the paid reply the // same way the main conversation path does and read the response from // the chat it actually landed in. const { chat: replyChat } = await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: reply, model: modelName, thinkingTimeMs, }); const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply, model: modelName, thinkingTimeMs, clientActions: [], }; } async function runRestrictedDirectToolFlow({ userEmail, chat, userIp, toolName, toolArgs, model = "adpanel-restricted-router", suppressQueuedReply = false, }) { const clientActions = []; const startedAt = Date.now(); const toolResult = await runTool({ name: toolName, args: toolArgs, userEmail, userIp, clientActions, }); const thinkingTimeMs = Date.now() - startedAt; const browserActionQueued = !!toolResult?.browserActionQueued; const reply = suppressQueuedReply && browserActionQueued ? "" : ( buildReplyFromToolResult(toolName, toolResult) || String(toolResult?.error || toolResult?.detail || "That request failed.").trim() ); let replyChat = chat; if (reply) { // The tool call above ran outside the per-user rotation lock; re-home // the reply like every other post-call insert. replyChat = (await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: reply, model, thinkingTimeMs, })).chat; } const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply, model, thinkingTimeMs, clientActions, }; } async function executeAssistantConversation({ userEmail, chat, trimmedMessage, userIp, persistedMessages, requestedModel }) { const provider = getResolvedProvider(); const apiKey = getProviderKey(provider); if (!apiKey) { throw new Error(`${getProviderLabel(provider)} is not configured.`); } // Fail-closed legacy guard: this one check covers EVERY provider call the // conversation may make with the resolved key below (lightweight chat, // restricted single-shot plan, direct tool-result summarizer, the main // completion loop and the truncation continuation — plus the model-list // lookups model resolution performs). Refuse while the key still wears // the weak enc-v1 envelope and retirement is unconfirmed; a no-op during // the pre-first-attempt boot window and once retirement is confirmed. assertAssistantProviderKeyMigrated(provider); const directAccountFlow = detectDirectAccountFlowIntent(trimmedMessage); const directBulkPowerFlow = detectDirectBulkPowerIntent(trimmedMessage); const directSinglePowerFlow = detectDirectSinglePowerIntent(trimmedMessage); const directLoadLookup = detectDirectLoadLookupIntent(trimmedMessage); const directOpenSettings = detectDirectOpenSettingsIntent(trimmedMessage, persistedMessages); const restrictedFollowUp = looksLikeRestrictedAssistantFollowUp(trimmedMessage, persistedMessages); const likelyNeedsServerContext = messageLikelyNeedsAccessibleServerContext(trimmedMessage, persistedMessages); const accessibleServers = likelyNeedsServerContext ? await loadAccessibleServersForAssistant(userEmail) : []; const latestServerHint = likelyNeedsServerContext ? inferAssistantServerMention(trimmedMessage, accessibleServers) : null; const historyServerHint = likelyNeedsServerContext && !latestServerHint ? inferAssistantServerMentionFromHistory(persistedMessages, accessibleServers) : null; const inferredServerHint = latestServerHint || historyServerHint; const inferredServerName = String(inferredServerHint?.name || "").trim(); const inferredServerContextMessage = inferredServerName ? (latestServerHint ? `Latest user message most likely refers to accessible server "${inferredServerHint.displayName || inferredServerName}" (internal name: ${inferredServerName}). Use that server unless the user clearly names a different one.` : `The latest user message omits the server name, but the recent conversation was about accessible server "${inferredServerHint.displayName || inferredServerName}" (internal name: ${inferredServerName}). Use that server unless the user clearly names a different one.`) : ""; const directCreateFlow = !POWER_ONLY_ASSISTANT ? detectDirectCreateServerFlowIntent(trimmedMessage) : null; if (directCreateFlow && !messageMentionsPluginInstall(trimmedMessage)) { const clientActions = [{ type: "open_create_server_modal" }]; const replyChat = (await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: directCreateFlow.reply, model: "adpanel-create-server-router", })).chat; const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply: directCreateFlow.reply, model: "adpanel-create-server-router", thinkingTimeMs: 0, clientActions, }; } const directConsoleCheck = detectDirectConsoleCheckIntent(trimmedMessage, inferredServerName); const directServerLimits = detectDirectServerLimitsIntent(trimmedMessage, inferredServerName); const directServerInfo = detectDirectServerInfoIntent(trimmedMessage, inferredServerName); const directOpenServerPage = detectDirectOpenServerPageIntent(trimmedMessage, inferredServerName, persistedMessages); const explicitNavigationRequest = messageLooksLikeAssistantOpenRequest(trimmedMessage) || isShortAssistantNavigationShortcut(trimmedMessage); const unresolvedNavigationReply = !directOpenServerPage && !directOpenSettings && explicitNavigationRequest ? ( messageExplicitlyNamesAssistantServerSection(trimmedMessage) || /\b(?:server|servers?|page)\b/i.test(trimmedMessage) ? "I can't help with that server link right now." : (messageExplicitlyNamesAssistantSettingsDestination(trimmedMessage) ? "I can't help with that settings link right now." : "") ) : ""; const accountSecurityTopic = messageLooksLikeAccountSecurityTopic(trimmedMessage); const restrictedCapabilityRequested = !!directAccountFlow || accountSecurityTopic || !!directLoadLookup || !!directConsoleCheck || !!directServerLimits || !!directServerInfo || !!directOpenServerPage || !!directOpenSettings || !!unresolvedNavigationReply || !!restrictedFollowUp || !!detectAssistantPowerAction(trimmedMessage) || messageLooksLikeConsoleCheckRequest(trimmedMessage) || messageLooksLikeServerLimitsCheckRequest(trimmedMessage) || messageLooksLikeServerInfoRequest(trimmedMessage); const restrictedIntentSystemHint = buildRestrictedIntentSystemHint({ directAccountFlow, accountSecurityTopic, directServerInfo, directBulkPowerFlow, directSinglePowerFlow, directLoadLookup, directConsoleCheck, directServerLimits, directOpenServerPage, directOpenSettings, }); if (POWER_ONLY_ASSISTANT) { if (directBulkPowerFlow) { return runRestrictedDirectToolFlow({ userEmail, chat, userIp, toolName: "power_accessible_servers", toolArgs: { action: directBulkPowerFlow.action }, model: directBulkPowerFlow.model || "adpanel-power-router", }); } if (directSinglePowerFlow) { return runRestrictedDirectToolFlow({ userEmail, chat, userIp, toolName: "power_server", toolArgs: directSinglePowerFlow.args, model: directSinglePowerFlow.model || "adpanel-power-router", }); } if (directLoadLookup) { return runRestrictedDirectToolFlow({ userEmail, chat, userIp, toolName: directLoadLookup.toolName, toolArgs: directLoadLookup.args, model: directLoadLookup.model || "adpanel-load-router", suppressQueuedReply: true, }); } if (directAccountFlow) { return runRestrictedDirectToolFlow({ userEmail, chat, userIp, toolName: "open_account_flow", toolArgs: { flow: directAccountFlow.flow }, model: directAccountFlow.model || "adpanel-account-router", }); } if (directOpenServerPage) { return runRestrictedDirectToolFlow({ userEmail, chat, userIp, toolName: "open_server_page", toolArgs: directOpenServerPage.args, model: directOpenServerPage.model || "adpanel-navigation-router", }); } if (directOpenSettings) { return runRestrictedDirectToolFlow({ userEmail, chat, userIp, toolName: "open_settings_destination", toolArgs: directOpenSettings.args, model: directOpenSettings.model || "adpanel-settings-router", }); } if (unresolvedNavigationReply) { // This insert runs outside the per-user rotation lock like every other // post-call write; re-home it so a concurrent prune cannot FK-fail a // turn that already produced a reply. const replyChat = (await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: unresolvedNavigationReply, model: "adpanel-navigation-guard", thinkingTimeMs: 0, })).chat; const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply: unresolvedNavigationReply, model: "adpanel-navigation-guard", thinkingTimeMs: 0, clientActions: [], }; } if (!restrictedCapabilityRequested && !directBulkPowerFlow && !directSinglePowerFlow) { const instantSmallTalkReply = buildInstantSmallTalkReply(trimmedMessage); if (instantSmallTalkReply) { // Same lock-free insert as the navigation guard above; re-home it. const replyChat = (await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: instantSmallTalkReply, model: "adpanel-smalltalk-router", thinkingTimeMs: 0, })).chat; const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply: instantSmallTalkReply, model: "adpanel-smalltalk-router", thinkingTimeMs: 0, clientActions: [], }; } return completeLightweightAssistantChat({ provider, apiKey, userEmail, chat, trimmedMessage, persistedMessages, requestedModel, }); } if (directConsoleCheck) { return runRestrictedDirectToolFlow({ userEmail, chat, userIp, toolName: directConsoleCheck.toolName, toolArgs: directConsoleCheck.args, model: directConsoleCheck.model || "adpanel-console-router", suppressQueuedReply: true, }); } if (directServerLimits) { return runRestrictedDirectToolFlow({ userEmail, chat, userIp, toolName: directServerLimits.toolName, toolArgs: directServerLimits.args, model: directServerLimits.model || "adpanel-limits-router", suppressQueuedReply: true, }); } if (directServerInfo) { return runRestrictedDirectToolFlow({ userEmail, chat, userIp, toolName: directServerInfo.toolName, toolArgs: directServerInfo.args, model: directServerInfo.model || "adpanel-server-info-router", suppressQueuedReply: true, }); } const modelName = await resolveChatModelForProvider(provider, requestedModel); const conversationContextMessage = ""; const startedAt = Date.now(); const response = await buildRestrictedSingleShotPlan({ provider, apiKey, modelName, systemPrompt: buildSystemPrompt({ appName: "ADPanel", userEmail, powerOnly: true }), latestUserMessage: trimmedMessage, inferredServerContextMessage, restrictedIntentSystemHint, conversationContextMessage, persistedMessages, requestChatCompletion, }); const thinkingTimeMs = Date.now() - startedAt; if (response.status !== 200) { throw new Error(describeProviderError( getProviderLabel(provider), response.status, response.data?.error?.message || response.data?.error || response.data?.raw )); } const rawContent = normalizeMessageContent(response.data?.choices?.[0]?.message?.content); const parsedPlan = parseRestrictedAssistantPlan(rawContent); const fallbackPlan = buildRestrictedFallbackPlan({ trimmedMessage, directAccountFlow, directBulkPowerFlow, directSinglePowerFlow, directLoadLookup, directConsoleCheck, directServerLimits, directServerInfo, directOpenServerPage, directOpenSettings, }); const plannedToolName = normalizeRestrictedToolName(parsedPlan?.toolName); const fallbackToolName = normalizeRestrictedToolName(fallbackPlan.toolName); const hasExplicitLatestIntent = !!fallbackToolName; const selectedToolName = hasExplicitLatestIntent ? fallbackToolName : (plannedToolName || fallbackToolName); const fallbackToolArgs = selectedToolName === fallbackToolName && selectedToolName ? sanitizeRestrictedToolArgs(selectedToolName, fallbackPlan.toolArgs) : {}; const selectedToolArgs = selectedToolName && plannedToolName === selectedToolName ? sanitizeRestrictedToolArgs(selectedToolName, parsedPlan?.toolArgs) : {}; const mergedToolArgs = hasExplicitLatestIntent ? mergeRestrictedToolArgs(selectedToolArgs, fallbackToolArgs) : mergeRestrictedToolArgs(fallbackToolArgs, selectedToolArgs); const forcedLatestIntentOverride = !!(hasExplicitLatestIntent && plannedToolName && plannedToolName !== fallbackToolName); const clientActions = []; let finalContent = String(parsedPlan?.reply || "").trim(); let clientWillReply = false; if (selectedToolName) { const baseToolArgs = Object.keys(mergedToolArgs).length ? mergedToolArgs : fallbackPlan.toolArgs; const toolArgs = applyServerHintToToolArgs(selectedToolName, baseToolArgs, inferredServerName); const toolResult = await runTool({ name: selectedToolName, args: toolArgs, userEmail, userIp, clientActions, }); const toolReply = buildReplyFromToolResult(selectedToolName, toolResult) || String(toolResult?.error || toolResult?.detail || "").trim(); clientWillReply = !!toolResult?.browserActionQueued && toolResult?.ok !== false && CLIENT_REPLYING_RESTRICTED_TOOLS.has(selectedToolName); if (clientWillReply) { finalContent = ""; } else if (forcedLatestIntentOverride && toolReply) { finalContent = toolReply; } else if (!finalContent || toolResult?.ok === false || (toolResult?.browserActionQueued && replyClaimsActionSucceeded(finalContent))) { finalContent = toolReply || finalContent; } } else if (!finalContent) { finalContent = rawContent; } if (!finalContent && !clientWillReply) { finalContent = buildPowerOnlyCapabilityReply(); } let replyChat = chat; if (finalContent) { // The provider call and tool runs above ran outside the per-user // rotation lock; re-home the reply like every other post-call insert. replyChat = (await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: finalContent, model: modelName, thinkingTimeMs, })).chat; } const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply: finalContent, model: modelName, thinkingTimeMs, clientActions, }; } const directDiagnosisFlow = !POWER_ONLY_ASSISTANT ? detectDirectDiagnosisIntent(trimmedMessage, inferredServerName) : null; if (directDiagnosisFlow) { const clientActions = []; const toolResult = await runTool({ name: directDiagnosisFlow.toolName, args: directDiagnosisFlow.args, userEmail, userIp, clientActions, }); const reply = buildReplyFromToolResult(directDiagnosisFlow.toolName, toolResult) || String(toolResult?.error || toolResult?.detail || "That diagnosis request failed.").trim(); const replyChat = (await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: reply, model: directDiagnosisFlow.model, })).chat; const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply, model: directDiagnosisFlow.model, thinkingTimeMs: 0, clientActions, }; } const directMinecraftPropertyFlow = !POWER_ONLY_ASSISTANT ? detectDirectMinecraftPropertyIntent(trimmedMessage, inferredServerName) : null; if (directMinecraftPropertyFlow) { const clientActions = []; const toolResult = await runTool({ name: directMinecraftPropertyFlow.toolName, args: directMinecraftPropertyFlow.args, userEmail, userIp, clientActions, }); const reply = buildReplyFromToolResult(directMinecraftPropertyFlow.toolName, toolResult) || String(toolResult?.error || toolResult?.detail || "That Minecraft update failed.").trim(); const replyChat = (await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: reply, model: directMinecraftPropertyFlow.model, })).chat; const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply, model: directMinecraftPropertyFlow.model, thinkingTimeMs: 0, clientActions, }; } const directFileInspectFlow = !POWER_ONLY_ASSISTANT ? detectDirectFileInspectIntent(trimmedMessage, inferredServerName) : null; if (directFileInspectFlow) { const clientActions = []; const toolResult = await runTool({ name: directFileInspectFlow.toolName, args: directFileInspectFlow.args, userEmail, userIp, clientActions, }); const reply = toolResult?.ok ? await summarizeDirectAssistantToolResult({ provider, apiKey, userMessage: trimmedMessage, toolName: directFileInspectFlow.toolName, toolResult, requestedModel, }) : (buildReplyFromToolResult(directFileInspectFlow.toolName, toolResult) || String(toolResult?.error || toolResult?.detail || "That file request failed.").trim()); const replyChat = (await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: reply, model: directFileInspectFlow.model, })).chat; const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply, model: directFileInspectFlow.model, thinkingTimeMs: 0, clientActions, }; } const createConversationLikely = isCreateServerConversation(trimmedMessage, persistedMessages); if (createConversationLikely && !messageMentionsPluginInstall(trimmedMessage)) { const clientActions = []; const provisioningResult = await maybeRunProvisioningFallback({ userEmail, userIp, trimmedMessage, persistedMessages, clientActions, }); if (provisioningResult) { const replyChat = (await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: provisioningResult.reply, model: provisioningResult.model || "adpanel-provisioning-router", })).chat; const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply: provisioningResult.reply, model: provisioningResult.model || "adpanel-provisioning-router", thinkingTimeMs: 0, clientActions, }; } } const provisioningContext = await inferProvisioningContext(persistedMessages); const conversationContextMessage = buildConversationContextMessage(provisioningContext); const { olderContextMessage, recentMessages } = buildAssistantModelConversationWindow(persistedMessages, { recentCount: 18, olderTranscriptCount: 10, olderTranscriptTotalLimit: 1400, }); const modelMessages = [ { role: "system", content: buildSystemPrompt({ appName: "ADPanel", userEmail, powerOnly: POWER_ONLY_ASSISTANT }), }, ...(inferredServerContextMessage ? [{ role: "system", content: inferredServerContextMessage }] : []), ...(restrictedIntentSystemHint ? [{ role: "system", content: restrictedIntentSystemHint }] : []), ...(conversationContextMessage ? [{ role: "system", content: conversationContextMessage }] : []), ...(olderContextMessage ? [{ role: "system", content: olderContextMessage }] : []), ...recentMessages, ]; const clientActions = []; const modelName = await resolveChatModelForProvider(provider, requestedModel); let responseModel = modelName; const allowToolUse = shouldAllowToolUseForMessage(trimmedMessage, persistedMessages) || !!directAccountFlow || !!directBulkPowerFlow || !!directSinglePowerFlow || !!directLoadLookup || !!directConsoleCheck || !!restrictedCapabilityRequested; const needsRealActionExecution = messageNeedsRealActionExecution(trimmedMessage); let thinkingTimeMs = 0; let finalContent = ""; let lastToolName = ""; let lastToolResult = null; let forcedToolReply = ""; for (let attempt = 0; attempt < ASSISTANT_MAX_LOOPS; attempt += 1) { const startedAt = Date.now(); const completionPayload = { model: modelName, temperature: 0.2, max_tokens: needsRealActionExecution ? 900 : 700, messages: modelMessages, }; if (allowToolUse) { completionPayload.tool_choice = "auto"; completionPayload.tools = POWER_ONLY_ASSISTANT ? POWER_TOOL_DEFINITIONS : TOOL_DEFINITIONS; } const response = await requestChatCompletion(provider, apiKey, completionPayload); thinkingTimeMs += Date.now() - startedAt; if (response.status !== 200) { throw new Error(describeProviderError( getProviderLabel(provider), response.status, response.data?.error?.message || response.data?.error || response.data?.raw )); } const choice = response.data?.choices?.[0] || {}; const message = choice.message; const finishReason = String(choice.finish_reason || "").trim().toLowerCase(); if (!message) { throw new Error(`${getProviderLabel(provider)} returned an empty response.`); } if (Array.isArray(message.tool_calls) && message.tool_calls.length > 0) { modelMessages.push({ role: "assistant", content: normalizeMessageContent(message.content), tool_calls: message.tool_calls, }); let powerToolUsedThisTurn = false; let lastWriteToolResultThisTurn = null; for (const call of message.tool_calls) { if ( isGenericServerPropertiesWriteToolCall(call?.function?.name, call?.function?.arguments) && messageLooksLikeStructuredMinecraftPropertyMutation(trimmedMessage) ) { const toolResult = { ok: false, error: "Use the Minecraft property updater for server.properties key changes.", }; lastToolName = String(call?.function?.name || "").trim(); lastToolResult = toolResult; modelMessages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(toolResult), }); continue; } const toolResult = await runTool({ name: call?.function?.name, args: applyServerHintToToolArgs(call?.function?.name, call?.function?.arguments, inferredServerName), userEmail, userIp, clientActions, }); lastToolName = String(call?.function?.name || "").trim(); lastToolResult = toolResult; if (lastToolName === "power_server" || lastToolName === "power_accessible_servers") { powerToolUsedThisTurn = true; } if (lastToolName === "write_file" && toolResult?.ok !== false) { lastWriteToolResultThisTurn = toolResult; } modelMessages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(toolResult), }); } if (!powerToolUsedThisTurn && lastWriteToolResultThisTurn?.server) { const chainedPowerAction = extractChainedPowerAction(trimmedMessage); if (chainedPowerAction) { const powerToolResult = await runTool({ name: "power_server", args: { server: lastWriteToolResultThisTurn.server, action: chainedPowerAction, }, userEmail, userIp, clientActions, }); lastToolName = "power_server"; lastToolResult = powerToolResult; forcedToolReply = buildWriteThenPowerReply(lastWriteToolResultThisTurn, powerToolResult); // no break here: fall through to the forcedToolReply check below, // which sets finalContent and exits the loop. breaking here would // leave finalContent empty and trigger the tool-limit throw. } } if (forcedToolReply) { finalContent = forcedToolReply; break; } continue; } finalContent = normalizeMessageContent(message.content); if (forcedToolReply) { finalContent = forcedToolReply; } if (shouldForceQueuedReply(lastToolName, lastToolResult)) { finalContent = buildReplyFromToolResult(lastToolName, lastToolResult) || finalContent; } if (lastToolResult?.browserActionQueued && replyClaimsActionSucceeded(finalContent)) { finalContent = buildReplyFromToolResult(lastToolName, lastToolResult) || finalContent; } if (isGenericAssistantReply(finalContent) && lastToolResult) { finalContent = buildReplyFromToolResult(lastToolName, lastToolResult) || finalContent; } if (isGenericAssistantReply(finalContent) && allowToolUse && !lastToolResult) { finalContent = "I need one more detail before I can do that."; } if (needsRealActionExecution && !lastToolResult && replyClaimsActionSucceeded(finalContent)) { finalContent = "I need one more detail before I can do that."; } if (!lastToolResult && messageLooksLikeBusiestLookup(trimmedMessage) && !/[?]/.test(finalContent)) { finalContent = /\b(node|nodes|nod|noduri)\b/i.test(trimmedMessage) ? "I can check that live. Say which node metric you want, or just say busiest node." : "I can check that live. Say busiest server, or name a metric like CPU or RAM."; } if (!lastToolResult && messageLooksLikeDiagnosisRequest(trimmedMessage) && !/[?]/.test(finalContent)) { finalContent = "Tell me which server to diagnose."; } if (!lastToolResult && messageLooksLikeConsoleCheckRequest(trimmedMessage) && !/[?]/.test(finalContent)) { finalContent = extractAssistantServerCandidate(trimmedMessage) ? "I can check that console now." : "Tell me which server console to check."; } if (!lastToolResult && detectAssistantPowerAction(trimmedMessage) && !detectDirectBulkPowerIntent(trimmedMessage) && !/[?]/.test(finalContent)) { finalContent = extractAssistantServerCandidate(trimmedMessage) ? "I can run that power action now." : "Tell me which server to start, stop, restart, or kill."; } if (!lastToolResult && messageLooksLikeMinecraftBatchPropertyUpdate(trimmedMessage) && !/[?]/.test(finalContent)) { finalContent = "Tell me the exact server.properties key and value to apply."; } if (!lastToolResult && messageLooksLikeStructuredMinecraftPropertyMutation(trimmedMessage) && !/[?]/.test(finalContent)) { finalContent = "Tell me which server to change, or say all accessible Minecraft servers."; } if (!finalContent) { finalContent = buildReplyFromToolResult(lastToolName, lastToolResult) || "Done."; } if (finishReason === "length" && finalContent) { finalContent = await continueTruncatedReply({ provider, apiKey, modelName, modelMessages, partialContent: finalContent, }); } break; } const exploratoryProvisioningTool = ["list_nodes", "list_templates"].includes(lastToolName); if (createConversationLikely && isVagueProvisioningReply(finalContent) && (!lastToolResult || exploratoryProvisioningTool)) { const fallbackResult = await maybeRunProvisioningFallback({ userEmail, userIp, trimmedMessage, persistedMessages, clientActions, }); if (fallbackResult) { finalContent = fallbackResult.reply; lastToolName = fallbackResult.toolName; lastToolResult = fallbackResult.toolResult; responseModel = fallbackResult.model || responseModel; } } if (!finalContent) { throw new Error("The assistant reached its tool limit before finishing."); } // The reply was already paid for, but the chat resolved at the start of // the turn may have been rotated away (cascade-deleted) mid-conversation // by a concurrent turn. Land it in the user's live chat — the rotation // leaves a fresh chat with a carry-forward summary, so context stays // coherent — and read the response from the chat the reply landed in. const { chat: replyChat } = await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: finalContent, model: responseModel, thinkingTimeMs, }); const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply: finalContent, model: responseModel, thinkingTimeMs, clientActions, }; } async function completeChat({ userEmail, chatId, userMessage, userIp, requestedModel }) { const trimmedMessage = String(userMessage || "").trim(); if (!trimmedMessage) { throw new Error("A message is required."); } // Reject before persistence, title generation and prompt embedding so // stored content and prompt content are the same bounded text. if (trimmedMessage.length > ASSISTANT_USER_MESSAGE_MAX_CHARS) { throw new Error(`Your message is too long (max ${ASSISTANT_USER_MESSAGE_MAX_CHARS} characters).`); } const chat = await getActiveChat(userEmail, chatId); if (!chat) { throw new Error("The assistant chat could not be found."); } // The user insert runs outside the rotation lock, so the chat resolved // above can be rotated away (cascade-deleted) before it lands. Re-home it // into the user's live chat and keep the whole turn — title update, model // history, conversation and final reply — on that chat. const { chat: liveChat } = await rehomeAssistantMessage(userEmail, chat.id, { role: "user", content: trimmedMessage }); await maybeUpdateChatTitle(liveChat.id, trimmedMessage); const persistedMessages = await getChatMessages(liveChat.id, CHAT_HISTORY_LIMIT); return executeAssistantConversation({ userEmail, chat: liveChat, trimmedMessage, userIp, persistedMessages, requestedModel, }); } // Keep the per-session pending-delete-intent store bounded and fresh: // expired entries are dropped on every touch, and the oldest entries are // evicted past the cap so a client minting many intents cannot grow the // shared Redis session blob. function pruneDeleteIntents(req) { const store = req?.session?.assistantDeleteIntents; if (!store || typeof store !== "object") return; const now = Date.now(); for (const [key, entry] of Object.entries(store)) { if (!entry || Number(entry.expiresAt || 0) <= now) { delete store[key]; } } const entries = Object.entries(store); if (entries.length <= DELETE_INTENT_MAX_PENDING_PER_SESSION) return; entries .sort((a, b) => Number(a[1]?.issuedAt || 0) - Number(b[1]?.issuedAt || 0)) .slice(0, entries.length - DELETE_INTENT_MAX_PENDING_PER_SESSION) .forEach(([key]) => delete store[key]); } // Mint + register one pending delete intent. Callers must have already // validated the admin, the chat ownership and the server — this primitive // deliberately performs no authorization of its own so the step-up failure // path can re-mint synchronously without re-running DB checks. function mintDeleteIntent({ req, chatId, serverName, displayName = "" }) { if (!req?.session) { throw new Error("A valid session is required."); } const resolvedName = String(serverName || "").trim(); if (!resolvedName) { throw new Error("A server name is required."); } if (typeof deps.issueActionToken !== "function") { throw new Error("Server deletion is not available here."); } const intentId = crypto.randomBytes(16).toString("hex"); const issuedAt = Date.now(); const expiresAt = issuedAt + DELETE_INTENT_TTL_MS; const resolvedDisplayName = String(displayName || "").trim() || resolvedName; const actionToken = deps.issueActionToken( req, ASSISTANT_DELETE_CONFIRM_ACTION, { intentId, chatId, serverName: resolvedName }, { ttlSeconds: Math.max(30, Math.round(DELETE_INTENT_TTL_MS / 1000)), oneTime: true } ); pruneDeleteIntents(req); if (!req.session.assistantDeleteIntents || typeof req.session.assistantDeleteIntents !== "object") { req.session.assistantDeleteIntents = {}; } req.session.assistantDeleteIntents[intentId] = { chatId, serverName: resolvedName, displayName: resolvedDisplayName, issuedAt, expiresAt, }; return { intentId, actionToken, expiresAt, chatId, server: { name: resolvedName, displayName: resolvedDisplayName, }, }; } // Validate and create a pending delete intent for the assistant confirmation // modal: admin only, bound to a chat this user owns, bound to a server that // exists under its canonical name. async function createDeleteIntent({ req, userEmail, chatId, serverName }) { const normalizedName = String(serverName || "").trim(); if (!normalizedName) { throw new Error("A server name is required."); } if (!req?.session) { throw new Error("A valid session is required."); } const currentUser = await deps.findUserByEmail(userEmail); if (!(currentUser && currentUser.admin)) { throw new Error("Admin required."); } // Bind the intent to a chat this user actually owns so a minted intent can // never detach from the conversation that requested it. Strict lookup (no // rotation side effects) so the same chat id is validated here and at // confirm time. const chat = await getChatById(userEmail, chatId); if (!chat) { throw new Error("The assistant chat could not be found."); } // Resolve strictly against the servers index by canonical name — the same // visibility an admin has in the tool layer. The intent token resource // binds this canonical name and is compared verbatim at confirm time. const index = typeof deps.loadServersIndex === "function" ? (await deps.loadServersIndex()) || [] : []; const needle = normalizedName.toLowerCase(); const entry = (Array.isArray(index) ? index : []).find( (item) => item && String(item.name || "").trim().toLowerCase() === needle ); if (!entry) { throw new Error("That server could not be found."); } const resolvedName = String(entry.name || "").trim() || normalizedName; const resolvedDisplayName = String(entry.displayName || "").trim() || resolvedName; const minted = mintDeleteIntent({ req, chatId: chat.id, serverName: resolvedName, displayName: resolvedDisplayName, }); const revokeSecurity = typeof deps.getDestructiveActionSecurityAsync === "function" ? await deps.getDestructiveActionSecurityAsync(req, currentUser) : null; return { ...minted, revokeSecurity }; } async function confirmDeleteServer({ userEmail, chatId, serverName, userIp, authMethod = null }) { const normalizedName = String(serverName || "").trim(); if (!normalizedName) { throw new Error("A server name is required."); } const currentUser = await deps.findUserByEmail(userEmail); if (!(currentUser && currentUser.admin)) { throw new Error("Admin required."); } if (typeof deps.deleteServerByName !== "function") { throw new Error("Server deletion is not available here."); } // Resolve the chat BEFORE the destructive call: a bookkeeping failure must // never land after an irreversible delete (the old ordering deleted first // and could then throw on a missing chat). const chat = await getChatById(userEmail, chatId); if (!chat) { throw new Error("The assistant chat could not be found."); } const result = await deps.deleteServerByName(normalizedName); if (!result?.ok) { throw new Error(result?.error || "Server deletion failed."); } // Cache parity with DELETE /api/settings/servers/:name: neither the server // index cache nor the per-server status TTL cache may keep serving the // deleted server after an assistant-initiated delete. if (typeof deps.invalidateServerIndexCache === "function") { try { deps.invalidateServerIndexCache(); } catch { } } if (typeof deps.deleteStatusCacheEntry === "function") { try { deps.deleteStatusCacheEntry(normalizedName); } catch { } } // Audit parity with the admin delete route: a per-server record and a // _system record, both carrying deletedBy, the actor, how the step-up was // satisfied (fresh credential vs scoped grace grant) and a // trusted-proxy-resolved IP supplied by the route. const actorEmail = String(currentUser.email || userEmail || "").trim().toLowerCase(); if (typeof deps.recordActivity === "function") { try { const auditDetails = { deletedBy: actorEmail, via: "dashboard-assistant", ...(authMethod ? { stepUp: authMethod } : {}), }; deps.recordActivity(normalizedName, "server_delete", auditDetails, actorEmail, userIp); deps.recordActivity("_system", "server_delete", { server: normalizedName, ...auditDetails }, actorEmail, userIp); } catch (actErr) { console.warn("[dashboard-assistant] Failed to record delete activity:", actErr?.message || actErr); } } const reply = `Deleted ${normalizedName}.`; // The delete call above ran outside the per-user rotation lock; re-home // the confirmation like every other post-call insert so a rotation during // the delete cannot 500 after the server is already gone. const { chat: replyChat } = await rehomeAssistantMessage(userEmail, chat.id, { role: "assistant", content: reply, model: "adpanel-delete-confirm", }); const freshChat = (await getChatById(userEmail, replyChat.id)) || replyChat; const freshMessages = await getChatMessages(replyChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply, model: "adpanel-delete-confirm", thinkingTimeMs: 0, clientActions: [], deleting: result.deleting === true, }; } async function completeClientFollowUp({ userEmail, chatId, summary, sourceType, context, requestedModel, skipAi = false }) { const verifiedSummary = String(summary || "").trim(); if (!verifiedSummary) { throw new Error("A follow-up summary is required."); } // The summary is persisted as the assistant reply and embedded in the // provider prompt, so it must be bounded before either happens. if (verifiedSummary.length > ASSISTANT_FOLLOWUP_SUMMARY_MAX_CHARS) { throw new Error(`Your follow-up summary is too long (max ${ASSISTANT_FOLLOWUP_SUMMARY_MAX_CHARS} characters).`); } const chat = await getActiveChat(userEmail, chatId); if (!chat) { throw new Error("The assistant chat could not be found."); } const provider = getResolvedProvider(); const apiKey = getProviderKey(provider); const recentMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); const lastUserText = getRecentMessagesByRole(recentMessages, "user", 1)[0] || ""; const recentVisibleTranscript = buildCarryForwardVisibleTranscript(recentMessages, { count: 8, perMessageLimit: 160, totalLimit: 1200, }); const compactContext = context && typeof context === "object" ? JSON.stringify(context).slice(0, ASSISTANT_FOLLOWUP_CONTEXT_MAX_CHARS) : ""; let reply = verifiedSummary; // Trust boundary: client-supplied text is never persisted as role // "assistant" — a fabricated assistant turn would re-enter later model // context as the model's own trusted history. reply is only flagged as // model output when a real provider completion produced it; client text // stays flagged false and is persisted under the "user" role below. let replyIsModelOutput = false; let thinkingTimeMs = 0; let responseModel = skipAi ? "adpanel-client-local" : "adpanel-client-follow-up"; if (!skipAi && apiKey) { // Fail-closed legacy guard: this follow-up path resolves its own key and // both the model resolution below and the conditional completion call can // put it on the wire, so assert before either happens. With no resolvable // key (or a skipAi follow-up over an unconfigured provider) the guard // no-ops and the pre-existing client-local fallback below runs as before. assertAssistantProviderKeyMigrated(provider); const modelName = await resolveChatModelForProvider(provider, requestedModel); const startedAt = Date.now(); const response = await requestChatCompletion(provider, apiKey, { model: modelName, temperature: 0.1, max_tokens: 700, messages: [ { role: "system", content: [ "You are ADPanel Assistant inside the ADPanel dashboard.", "Always reply in English.", "Keep replies very short, natural, and good for speech.", "The browser already executed the action and produced verified result data.", "Answer using only that verified result and the visible conversation context.", "Do not mention the browser, tools, routing, JSON, or internal mechanics.", "If the verified result already answers the user, say it directly.", "Answer only what the user actually asked. Do not recite every metric in the verified result.", "If the action type is console_check, interpret the logs and status directly for the user.", "If the action type is server_limits_check and the user asked about one resource such as storage, RAM, or CPU, answer with that resource only.", "Only mention a resource the user did not ask about when it looks dangerously high, and keep that to one short heads-up.", "When RAM, CPU, or storage looks dangerously high, say that clearly and suggest checking the console next.", "If the action type is busiest_server or busiest_node, name the busiest one and answer with the metrics the user asked about.", "If the action type is server_overview, answer the asked fact exactly from the verified overview data: template, node, IP, port, version, fork, or backups.", "If a fact the user asked about is missing or null in the verified data, say you do not have that information. Never guess or invent values like IPs, node names, templates, or backup counts.", "If the user asked whether usage is good or healthy, give a clear yes or no based on the verified numbers, then the key number.", "If the verified result says a server could not be matched, say that plainly and offer the candidate names. Never invent data for an unmatched server.", "Prefer the raw log lines and verified status over any prewritten summary when they are available.", "If startup timing is visible in the verified result, state the seconds clearly.", "If the user asks whether the server started correctly or is healthy, answer that directly from the logs and status.", "Do not just repeat the verified summary if the log lines let you answer more precisely.", ].join(" "), }, { role: "user", content: [ recentVisibleTranscript ? `Recent visible chat:\n${recentVisibleTranscript}` : "", lastUserText ? `Last user request: ${lastUserText}` : "", sourceType ? `Action type: ${String(sourceType).trim().slice(0, ASSISTANT_FOLLOWUP_SOURCETYPE_MAX_CHARS)}` : "", `Verified result summary: ${verifiedSummary}`, compactContext ? `Extra verified context JSON: ${compactContext}` : "", ].filter(Boolean).join("\n\n"), }, ], }); thinkingTimeMs = Date.now() - startedAt; responseModel = modelName; if (response.status === 200) { const aiReply = normalizeMessageContent(response.data?.choices?.[0]?.message?.content); if (aiReply) { reply = aiReply; replyIsModelOutput = true; } } } // Client-provided summaries (skipAi follow-ups, and the fallback when the // provider call fails or returns empty) are stored as "user" rows: the // context builder replays them only as user input, never as assistant // history. Only genuine provider output earns the "assistant" role. // Same rotation race as completeChat: the provider call above ran outside // the per-user lock, so re-home the reply into the user's live chat (the // role choice describes content provenance and is unaffected) and read // the response from the chat it actually landed in. const { chat: followUpChat } = await rehomeAssistantMessage(userEmail, chat.id, { role: replyIsModelOutput ? "assistant" : "user", content: reply, model: responseModel, thinkingTimeMs, }); const freshChat = (await getChatById(userEmail, followUpChat.id)) || followUpChat; const freshMessages = await getChatMessages(followUpChat.id, VISIBLE_CHAT_HISTORY_LIMIT); return { chat: freshChat, messages: freshMessages, reply, model: responseModel, thinkingTimeMs, clientActions: [], }; } async function getBootstrap(req) { const userEmail = String(req.session?.user || "").trim().toLowerCase(); const currentUser = await deps.findUserByEmail(userEmail); // getActiveChat can return null when a cross-process prune deleted the // user's only chat mid-resolution; bootstrap must always hand back a // usable chat. let chat = await getActiveChat(userEmail); if (!chat) { chat = await createFreshChat(userEmail); } const messages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); const activeProvider = getResolvedProvider(); const activeKey = getProviderKey(activeProvider); // Effective chat model for the active provider, so the picker can show // what the assistant actually runs. Resolution may await the provider's // live model list (cached, 10 min TTL) — acceptable at bootstrap time. // modelLocked reports an env override pin: the client then stops sending // model picks because the pin wins server-side regardless. const effectiveChatModel = await resolveChatModelForProvider(activeProvider); const modelOverridePinned = !!(ensureProviderSecretCache().modelOverrides || {})[activeProvider]; const canConfigure = !!(currentUser && currentUser.admin); const assistantConfig = typeof deps.getDashboardAssistantConfig === "function" ? deps.getDashboardAssistantConfig() : { allowNormalUsers: false }; const actionTokens = {}; if (canConfigure && typeof deps.issueActionToken === "function") { actionTokens.saveToken = deps.issueActionToken(req, "POST /api/dashboard-assistant/token", {}, { ttlSeconds: 300 }); actionTokens.updateAccess = deps.issueActionToken(req, "POST /api/dashboard-assistant/access", {}, { ttlSeconds: 300 }); } const providers = Object.keys(PROVIDER_LABELS).map((providerId) => { const key = getProviderKey(providerId); return { id: providerId, label: getProviderLabel(providerId), configured: !!key, obscuredValue: canConfigure ? buildStoredKeyFieldValue(key) : "", }; }); if (!canConfigure) { return { configured: !!activeKey, canConfigure: false, allowNormalUsers: !!assistantConfig.allowNormalUsers, model: effectiveChatModel, modelLocked: modelOverridePinned, chat, messages, actionTokens: {}, providers: [], user: currentUser ? { email: currentUser.email, admin: false, } : null, }; } // Admin-only crypto-hygiene surfacing: while the enc-v1 → enc-v2 key // migration has been attempted but retirement is unconfirmed AND a stored // provider key still wears the legacy enc-v1 envelope, the chat paths // refuse to exercise that key (fail-closed legacy guard). That condition // is otherwise invisible until a chat actually fails, so the admin // bootstrap mirrors it proactively. Envelope versions are read through the // live secret cache (not a one-shot .env snapshot) so a re-saved enc-v2 key // clears legacyPending without a restart, and the boot window (first // migration attempt not yet run) reports legacyPending false — retirement // is merely unconfirmed there, exactly when the guard is still permissive. // orphanedKeys counts providers whose ORPHANED_V1 quarantine slot holds a // recovery artifact (a persistently-undecryptable enc-v1 value the // migration moved out of its live slot) — the operator-visible hint that // manual recovery or cleanup is available, and that the live config is // enc-v1-free regardless. Secret-free by construction: the migration // state getter, the envelope versions and the occupancy booleans are // curated primitives, never key material. Normal users get no // keyMigration at all: they have no remediation power and need no // crypto-hygiene detail. const migrationState = getAssistantProviderSecretMigrationState(); const legacyEnvelopeStored = Object.keys(PROVIDER_LABELS).some( (providerId) => getStoredEnvelopeVersion(providerId) === ASSISTANT_PROVIDER_SECRET_VERSION ); const cachedOrphanedV1 = ensureProviderSecretCache().orphanedV1 || {}; const orphanedKeys = Object.keys(PROVIDER_LABELS).reduce( (sum, providerId) => sum + (cachedOrphanedV1[providerId] ? 1 : 0), 0 ); return { configured: !!activeKey, provider: activeProvider, providerLabel: getProviderLabel(activeProvider), providers, canConfigure, allowNormalUsers: !!assistantConfig.allowNormalUsers, model: effectiveChatModel, modelLocked: modelOverridePinned, chat, messages, actionTokens, user: currentUser ? { email: currentUser.email, admin: !!currentUser.admin, } : null, keyMigration: { legacyPending: !!(migrationState.attempted && !migrationState.retired && legacyEnvelopeStored), retired: !!migrationState.retired, attempted: !!migrationState.attempted, lastFailureReason: String(migrationState.lastFailureReason || ""), orphanedKeys, }, }; } async function getModelsForProvider({ provider }) { const cleanProvider = sanitizeProvider(provider) || "groq"; try { const apiKey = getProviderKey(cleanProvider); if (apiKey) { const ids = await getLiveChatModelIds(cleanProvider); if (ids.length) { return ids.map((modelId) => ({ value: modelId, label: formatModelDisplayName(modelId) })); } } } catch (error) { console.warn("[dashboard-assistant] getModelsForProvider fallback error:", error?.message); } return DEFAULT_MODELS[cleanProvider] || DEFAULT_MODELS.groq || []; } const accountOperation = (operation) => (params) => history.runForUser(params.userEmail, () => operation(params), params.userId); return { ensureTables, getBootstrap: (req) => history.runForUser(req.session?.user, () => getBootstrap(req), req.session?.accountId || req.currentUser?.id), createFreshChat: (email, userId) => history.runForUser(email, () => createFreshChat(email), userId), resetChat: (email, userId) => history.runForUser(email, () => resetChat(email), userId), getPrimaryChat: (email, userId) => history.runForUser(email, () => getPrimaryChat(email), userId), saveProviderToken, getModelsForProvider, resolveChatModelForProvider, transcribeAudio, completeChat: accountOperation(completeChat), completeClientFollowUp: accountOperation(completeClientFollowUp), createDeleteIntent: (params) => history.runForUser(params.userEmail, () => createDeleteIntent(params), params.req?.session?.accountId || params.req?.currentUser?.id), mintDeleteIntent, confirmDeleteServer: accountOperation(confirmDeleteServer), }; } module.exports = { createDashboardAssistantService, DEFAULT_CHAT_TITLE, DELETE_INTENT_TTL_MS, ASSISTANT_DELETE_CONFIRM_ACTION, ASSISTANT_USER_MESSAGE_MAX_CHARS, ASSISTANT_FOLLOWUP_SUMMARY_MAX_CHARS, encryptAssistantProviderToken, decryptAssistantProviderToken, migrateAssistantProviderSecretsV1ToV2, getAssistantProviderSecretMigrationState, inferTranscriptionFilename, sanitizeTranscriptionFilename, };