Files
Kelx/utils/dashboard-assistant-tools.js
2026-11-30 16:32:37 +00:00

3427 lines
151 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
const path = require("path");
const { withKeyedLock } = require("./keyed-async-lock");
const {
extractTechnicalServerNameFromNodeCreateResult,
} = require("./server-startup-command");
const { sanitizeDockerTemplatePayload } = require("./server-template-payload");
const { resolveMcFork, resolveMcVersion, SUPPORTED_MC_FORKS } = require("./minecraft-versions");
const { daemonRenameNewName } = require("./daemon-protocol");
// adpanel:backup-cap-daemon-enforced — the create_server tool transmits the
// panel's per-server backup cap as resources.backupsMax (resolved from the
// SAME env the scheduler/relay count checks read), so the daemon's op-lock
// bound and the panel's count-then-create fast-fail agree.
const { resolveBackupsMaxFromInput } = require("./backup-cap");
// adpanel:node-storage-name — the node daemon's filesystem-namespace
// sanitizer, mirrored here exactly like the node proxy (nodes.js) does. This
// is a pure util (no boot-time side effects), so unlike index.js helpers it
// is importable directly — see the NODE_FS_WRITE_BODY_LIMIT_BYTES_ASSISTANT
// note above for why index.js itself cannot be required here.
const { sanitizeNodeStorageName } = require("./server-name");
// adpanel:server-create-consolidation — the create_server tool's shared steps
// (name guards, ownership-guarded compensating delete, guarded index commit)
// run through the ONE shared server-creation service. This module requires
// the service directly (services requires only utils/* — no cycle:
// index.js → utils/dashboard-assistant-tools.js → services → utils).
const serverCreateService = require("../services/server-create");
// adpanel:relay-helper-consolidation — the assistant's private copies of the
// fs path helpers were the third copies of the relay layer's twins
// (utils/server-asset-apply.js carried the fourth, also re-bound); they are
// re-bound here from the ONE shared module. The flagged
// deltas are documented at each former definition site below.
const {
safeJoinUnix,
isServerRootResolvedPath,
decodeNodeFileReadContent,
} = require("../services/node-fs-relay");
const FILE_PREVIEW_LIMIT = 16000;
// Panel-side byte caps for the assistant's fs reads/writes. The daemon caps
// reads itself (io.LimitReader in handleFSRead), but the panel must not trust
// that: older daemons, other responders or a lying Content-Length must not
// control panel memory. The read cap bounds the node's RESPONSE body, and
// reads are fetched as base64, so the cap must carry raw × 4/3 + the JSON
// envelope: 2 MiB of file content encodes to exactly 4 × ceil(2097152 / 3) =
// 2,796,204 base64 chars, + 1 KiB envelope headroom → 2,797,228 (~2.67 MiB).
// A flat 2 MiB cap would have covered only ~1.5 MiB of raw content after the
// base64 switch; this restores ≥2 MiB effective raw coverage while the
// panel-memory bound grows just 2 MiB → ~2.67 MiB. The write cap bounds what
// one assistant turn can send.
const ASSISTANT_FS_READ_MAX_BYTES = 4 * Math.ceil((2 * 1024 * 1024) / 3) + 1024;
const ASSISTANT_FS_WRITE_MAX_BYTES = 1 * 1024 * 1024;
// Issue 7 port — duplicated from index.js (NODE_FS_WRITE_BODY_LIMIT_BYTES /
// NODE_FS_WRITE_TOO_LARGE_MARKER): this module cannot import index.js helpers
// (index.js boots servers on require). The daemon caps the RAW JSON body of
// /v1/fs/write at 10 MiB inclusive and answers an over-budget body with 400
// "content too large (max 10MB)" (malformed JSON answers "invalid JSON body").
const NODE_FS_WRITE_BODY_LIMIT_BYTES_ASSISTANT = 10 * 1024 * 1024;
const NODE_FS_WRITE_TOO_LARGE_MARKER_ASSISTANT = "content too large";
// Fuzzy server-name auto-selection bar. A non-exact match only resolves
// silently when it is clearly strong (score >= 220: only a compact-prefix hit
// or a very high token-overlap score, roughly >= 6 shared tokens, reaches
// this bar) AND the query carries enough text to be specific (>= 4 chars) AND
// it beats the runner-up by a clear margin. The length and margin gates are
// the primary protection; weaker hits return candidate choices instead of
// guessing which server was meant.
const SERVER_CONFIDENT_MATCH_SCORE = 220;
const SERVER_CONFIDENT_MATCH_MARGIN = 50;
const SERVER_MIN_CONFIDENT_QUERY_LENGTH = 4;
const MODRINTH_API_BASE = "https://api.modrinth.com/v2";
const MODRINTH_PLUGIN_LOADERS = Object.freeze([
"paper",
"purpur",
"spigot",
"bukkit",
"velocity",
"waterfall",
"bungeecord",
"fabric",
"quilt",
"forge",
"neoforge",
]);
const TOOL_DEFINITIONS = [
{
type: "function",
function: {
name: "list_templates",
description: "List the available ADPanel server templates that can be used for new servers.",
parameters: {
type: "object",
properties: {},
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "list_nodes",
description: "List the available nodes where new servers can be created.",
parameters: {
type: "object",
properties: {},
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "create_server",
description: "Create a new server from a chosen template on a chosen node. Use this only after you know the template, node, server name, host port, and the desired RAM/CPU/storage limits, unless the user explicitly asked to use defaults.",
parameters: {
type: "object",
properties: {
name: {
type: "string",
description: "The server name/ID to create.",
},
displayName: {
type: "string",
description: "Optional display name to show in the dashboard.",
},
templateId: {
type: "string",
description: "The ADPanel template id or name, such as 'minecraft' or 'nodejs'.",
},
nodeId: {
type: "string",
description: "The target node id, uuid, or name.",
},
hostPort: {
type: "number",
description: "The public port for the new server. If omitted, the template default port will be used when available.",
},
mcFork: {
type: "string",
description: "Optional Minecraft fork. One of: paper, pufferfish, vanilla, purpur. 'spigot' and 'bukkit' are accepted and mapped to paper.",
},
mcVersion: {
type: "string",
description: "Optional Minecraft version, e.g. 1.21.8, 1.21.8-pre1, or a snapshot id like 24w14a.",
},
importUrl: {
type: "string",
description: "Optional archive URL to import after creation.",
},
resources: {
type: "object",
properties: {
ramMb: { type: "number" },
cpuCores: { type: "number" },
storageMb: { type: "number" },
storageGb: { type: "number" },
swapMb: { type: "number" },
backupsMax: { type: "number" },
maxSchedules: { type: "number" },
},
additionalProperties: false,
},
},
required: ["name", "templateId", "nodeId"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "list_servers",
description: "List the servers the current user can access.",
parameters: {
type: "object",
properties: {},
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "install_plugin",
description: "Install a Minecraft plugin from Modrinth onto a server by downloading the correct file into the plugins folder. Use this for plugin requests such as ViaVersion, LuckPerms, Vault, Geyser, or similar.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The target server name as used inside ADPanel.",
},
pluginName: {
type: "string",
description: "The plugin name or slug to install from Modrinth.",
},
platform: {
type: "string",
description: "Optional loader/platform such as paper, purpur, spigot, bukkit, velocity, fabric, forge, or neoforge.",
},
gameVersion: {
type: "string",
description: "Optional Minecraft version such as 1.21.8.",
},
},
required: ["server", "pluginName"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "inspect_server",
description: "Inspect one server, including status, template, and the current user's permissions.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name as used inside ADPanel.",
},
},
required: ["server"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "get_busiest_node",
description: "Ask the browser to find the busiest node right now from live node stats. Admin only. Use this when the user asks which node is most loaded, busiest, hottest, or under the most pressure.",
parameters: {
type: "object",
properties: {
metric: {
type: "string",
enum: ["balanced", "cpu", "memory", "disk"],
description: "Optional load metric. Use balanced unless the user explicitly asks for CPU, memory, or disk.",
},
includeMetrics: {
type: "array",
items: {
type: "string",
enum: ["cpu", "memory", "disk"],
},
description: "Optional resource details to include in the spoken result when the user asks for CPU, RAM, or disk values.",
},
},
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "get_busiest_server",
description: "Ask the browser to find the busiest accessible server right now from live status data. Use this when the user asks which server is most loaded, busiest, or using the most resources.",
parameters: {
type: "object",
properties: {
metric: {
type: "string",
enum: ["balanced", "cpu", "memory", "disk"],
description: "Optional load metric. Use balanced unless the user explicitly asks for CPU, memory, or disk.",
},
includeMetrics: {
type: "array",
items: {
type: "string",
enum: ["cpu", "memory", "disk"],
},
description: "Optional resource details to include in the spoken result when the user asks for CPU, RAM, or disk values.",
},
},
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "check_server_console",
description: "Ask the browser to inspect the live console output for one accessible server and answer briefly from the console. Use this for console checks, recent errors, startup failures, crashes, or log-based diagnosis without reading files.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name or raw server reference from the user's request.",
},
question: {
type: "string",
description: "Optional short focus question, such as why it crashed or what the console shows.",
},
},
required: ["server"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "check_server_limits",
description: "Ask the browser to inspect one accessible server's live RAM, CPU, and storage usage against its current limits. Use this for questions about quotas, remaining RAM or disk, resource headroom, whether usage is too high, or whether a server is close to its limits.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name or raw server reference from the user's request.",
},
question: {
type: "string",
description: "Optional short focus question, such as how much RAM is left or whether the limits look healthy.",
},
includeMetrics: {
type: "array",
items: {
type: "string",
enum: ["cpu", "memory", "disk"],
},
description: "Optional resource details to emphasize when the user specifically asks about CPU, RAM, or disk.",
},
},
required: ["server"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "get_server_overview",
description: "Return verified facts about one accessible server: template, node, IP address, port, version, fork, last known status, and backups. Use this for any question about a server's details, such as what template it runs, which node hosts it, its IP or port, its version, or how many backups it has. Never answer those questions from memory.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name or raw server reference from the user's request.",
},
question: {
type: "string",
description: "Optional short focus question, such as what template it runs or how many backups it has.",
},
},
required: ["server"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "diagnose_server",
description: "Ask the browser to inspect one accessible server with live status, recent activity, and short log context, then return a short diagnosis. Use this for requests about crashes, startup problems, lag, instability, or why a server is failing.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name as used inside ADPanel.",
},
},
required: ["server"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "update_minecraft_server_property",
description: "Ask the browser to update one key inside server.properties on one named Minecraft server or across all accessible Minecraft servers the current user can edit. Use this for safe key/value changes like online-mode=false, motd, max-players, difficulty, pvp, whitelist, or view-distance.",
parameters: {
type: "object",
properties: {
property: {
type: "string",
description: "The exact server.properties key, such as online-mode, motd, max-players, pvp, whitelist, difficulty, spawn-protection, or view-distance.",
},
value: {
type: "string",
description: "The value to write, as plain text, such as false, true, 20, easy, or a motd string.",
},
scope: {
type: "string",
enum: ["single_server", "all_accessible_minecraft"],
description: "Use single_server for one named server or all_accessible_minecraft for every accessible Minecraft server.",
},
server: {
type: "string",
description: "Required when scope is single_server. The ADPanel server name to update.",
},
onlyIfCurrent: {
type: "string",
description: "Optional current-value guard. Use true or false when the user says to change it only if the current value matches.",
},
restartAfter: {
type: "boolean",
description: "Set true when the user also asked to restart after the write succeeds.",
},
},
required: ["property", "value", "scope"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "request_delete_server",
description: "Ask the browser to show a confirmation modal before deleting a server. Use this instead of deleting immediately.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name to delete.",
},
},
required: ["server"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "list_files",
description: "List files inside a server directory. Use this before reading or editing when you are unsure about the path.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name as used inside ADPanel.",
},
path: {
type: "string",
description: "A relative directory path inside the server, for example '' or 'plugins'.",
},
},
required: ["server"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "read_file",
description: "Read a text file from a server. Use this before changing an existing file unless the user already gave you the full replacement content.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name as used inside ADPanel.",
},
path: {
type: "string",
description: "The relative file path inside the server.",
},
},
required: ["server", "path"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "write_file",
description: "Create or replace a text file on a server.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name as used inside ADPanel.",
},
path: {
type: "string",
description: "The relative file path inside the server.",
},
content: {
type: "string",
description: "The complete file content that should be written.",
},
},
required: ["server", "path", "content"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "create_directory",
description: "Create a new directory on a server.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name as used inside ADPanel.",
},
path: {
type: "string",
description: "The relative directory path to create.",
},
},
required: ["server", "path"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "rename_path",
description: "Rename or move a file or directory on a server.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name as used inside ADPanel.",
},
source: {
type: "string",
description: "The current relative path.",
},
destination: {
type: "string",
description: "The new relative path.",
},
},
required: ["server", "source", "destination"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "delete_path",
description: "Delete a file or directory on a server.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name as used inside ADPanel.",
},
path: {
type: "string",
description: "The relative path to delete.",
},
isDirectory: {
type: "boolean",
description: "Set to true when the target is a directory.",
},
},
required: ["server", "path"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "power_server",
description: "Ask the browser to start, stop, restart, or kill one server when the current user has permission. For every accessible server at once, use power_accessible_servers instead.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The server name as used inside ADPanel.",
},
action: {
type: "string",
enum: ["start", "stop", "restart", "kill"],
description: "The power action to execute.",
},
},
required: ["server", "action"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "power_accessible_servers",
description: "Ask the browser to start, stop, restart, or kill every server the current user can access and control. Use this when the user says all servers, every server, or all accessible servers. Do not call power_server repeatedly for that.",
parameters: {
type: "object",
properties: {
action: {
type: "string",
enum: ["start", "stop", "restart", "kill"],
description: "The power action to execute for all eligible accessible servers.",
},
},
required: ["action"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "open_server_page",
description: "Open one accessible server in a new browser tab, optionally jumping straight to its console, backups, files, scheduler, activity, store, resource stats, reinstall, or info area.",
parameters: {
type: "object",
properties: {
server: {
type: "string",
description: "The target server name or the user's raw server wording.",
},
section: {
type: "string",
enum: [
"console",
"info",
"files",
"activity",
"backups",
"scheduler",
"store",
"resource_stats",
"reinstall",
"ai_help",
],
description: "Which part of the server page to open. Use console when the user just wants the server page.",
},
},
required: ["server"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "open_settings_destination",
description: "Open an admin-only ADPanel settings area or settings modal in a new browser tab. Use this for requests like nodes, appearance, branding, maintenance, captcha, databases, webhooks, or create user.",
parameters: {
type: "object",
properties: {
panel: {
type: "string",
enum: [
"preferences",
"customization",
"account",
"security",
"databases",
"nodes",
"templates",
"servers",
"webhooks",
"panelinfo",
],
description: "The settings category to open.",
},
action: {
type: "string",
enum: [
"create_user",
"branding",
"login_background",
"alert",
"database_setup",
"pgadmin_setup",
"mongodb_setup",
"captcha",
"maintenance",
"create_node",
"create_template",
"add_webhook",
],
description: "Optional modal or special settings action to open after the panel loads.",
},
},
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "open_account_flow",
description: "Open an existing ADPanel account flow in the browser for sensitive actions like password, email, or 2FA changes.",
parameters: {
type: "object",
properties: {
flow: {
type: "string",
enum: [
"change_password",
"change_email",
"change_2fa",
"recover_password",
"recover_email",
"recover_2fa",
],
description: "The account flow that should be opened.",
},
},
required: ["flow"],
additionalProperties: false,
},
},
},
];
// Frozen: the runner shares this exact Set reference, so an unfrozen export
// would let any consumer add() a name and silently widen the power gate.
// .has lookups are unaffected by freeze (it blocks add/delete only).
const POWER_TOOL_NAMES = Object.freeze(new Set([
"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",
]));
const POWER_TOOL_DEFINITIONS = TOOL_DEFINITIONS.filter((definition) =>
POWER_TOOL_NAMES.has(String(definition?.function?.name || "").trim())
);
function buildSystemPrompt({ appName = "ADPanel", userEmail, powerOnly = false }) {
if (powerOnly) {
return [
`You are ${appName} Assistant inside the ${appName} dashboard.`,
"Always reply in English.",
"Keep replies extremely short, natural, and easy to understand when spoken aloud.",
"Sound like a voice assistant, not a chatbot.",
"Default to one short sentence.",
"Use recent chat context for short follow-up questions about the last result.",
"You receive the visible chat history shown in the dashboard. Use it when the user refers to earlier messages.",
"Always prioritize the latest explicit user request over older context.",
"Use older context only to resolve omitted references like it, that server, there, or the last result.",
"If the latest user message explicitly names a server, page section, popup, settings area, or action, do not let older context override it.",
"If the answer is already in the recent conversation, answer it directly instead of listing capabilities.",
"You currently support only these capability groups: power actions for accessible servers, sharing direct links to accessible server pages, sharing direct links to admin-only settings navigation, account security popups, live busiest node/server checks, live server console checks, live per-server quota and limits checks, and verified server detail lookups (template, node, IP, port, version, backups).",
"Use power_server for one named server and power_accessible_servers for all accessible servers.",
"Use open_server_page when the user wants to open, manage, configure, edit, or access a server page, console, backups, files, scheduler, activity, info, store, reinstall, or resource stats through a direct link.",
"Use open_settings_destination for admin-only settings categories and settings modals such as nodes, appearance, branding, maintenance, captcha, databases, webhooks, or create user, and let the dashboard share a direct link.",
"Never claim a page or tab opened automatically. The dashboard will give the user a clickable link.",
"Use open_account_flow for password, email, and 2FA change or recovery requests.",
"Use get_busiest_node for admin requests about the busiest node right now, and get_busiest_server for the busiest accessible server.",
"Use check_server_console for console, crash, startup, error, and log questions about one accessible server.",
"Use check_server_limits for questions about one accessible server's RAM, CPU, disk, storage, free space, remaining headroom, quotas, or whether it is close to its limits.",
"Use get_server_overview for any question about a server's facts: its template, node, IP address, port, version, fork, or backups.",
"Never answer server facts like template, IP, port, node, version, or backup counts from memory. Always use get_server_overview for those.",
"If verified tool data does not include a fact the user asked for, say honestly that you do not have that information. Never invent values.",
"If the user asks how many seconds startup took, whether a server started correctly, whether it is running well, or what the logs show, treat that as a console-check request.",
"Users may mention a server by bare name, lowercase, with quotes, with parentheses, or in messy wording. Resolve the intended accessible server and call the power tool.",
"Do not ask the user to prefix the name with the word server when the intended server is already clear.",
"Normalize messy phrasing into one action and one target before calling a tool.",
"Only claim an action succeeded after the matching tool succeeded.",
"Do not read, write, edit, list, or inspect server files.",
"Do not inspect server files, install plugins, create servers, or delete servers in this restricted mode.",
"If the user asks for anything outside those allowed capabilities, say briefly what you can do right now.",
"If the server name is still unclear, ask one short direct question.",
`Current authenticated user: ${String(userEmail || "unknown").trim() || "unknown"}.`,
].join(" ");
}
return [
`You are ${appName} Assistant inside the ${appName} dashboard.`,
"Always reply in English.",
"Keep replies extremely short, natural, and easy to understand when spoken aloud.",
"Sound like a voice assistant, not a chatbot.",
"Default to one short sentence.",
"Use two short sentences only when the second sentence adds essential help.",
"Never give long explanations unless the user explicitly asks for detail.",
"Use previous messages as context, but always answer the user's latest message directly.",
"You receive the visible chat history shown in the dashboard. Use it when the user refers to earlier messages.",
"Do not ignore or override the user's latest request because of older context.",
"When an action succeeds, confirm it in one short sentence.",
"When you need missing information, ask one short direct question.",
"If you list choices, keep it to the best 3 options and keep the wording brief.",
"The wake phrase is optional. Respond normally even when the user does not say 'Hey ADPanel' first.",
"You can read context from previous messages in this chat and you can use tools to perform real ADPanel actions when they are actually needed.",
"Only claim an action succeeded after the matching tool succeeded.",
"If the user wants to change their password, email, or 2FA, never ask them to send secrets in chat. Use the open_account_flow tool instead.",
"If the user needs a recovery flow for password, email, or 2FA, use the matching recovery account flow instead of asking for sensitive codes in chat.",
"If a user wants to modify an existing file and you do not already have the current content, read the file first before writing a replacement.",
"When the user names a file path and a server, prefer reading or listing that path before saying it is unavailable.",
"If a request is missing critical details, ask one short follow-up question instead of guessing.",
"If the user lacks permission for an action, explain that clearly and do not attempt to bypass permissions.",
"General questions, casual chat, short phrases, or assistant-related questions should be answered directly without using server tools.",
"Use get_busiest_node for admin requests about the most loaded node right now.",
"Use get_busiest_server for requests about the most loaded accessible server right now.",
"Use diagnose_server for crash, startup, lag, and server health diagnosis requests.",
"Use update_minecraft_server_property for changing one server.properties value on one Minecraft server or across all accessible Minecraft servers.",
"Users may mention a server by its bare name, in lowercase, in parentheses, or without the word server. Treat that as the server reference when it matches an accessible server.",
"Do not ask the user to prefix a server name with the word server when the intended server is already clear.",
"For server.properties key changes, pass only the raw value like false or 40. Never include instructions such as 'if it is true' inside the value string.",
"If the user says to change a server.properties key only when it currently has a certain value, use onlyIfCurrent instead of writing that condition into the file content.",
"If the user also wants a restart after a server.properties update, set restartAfter true instead of describing restart inside the value.",
"When the user wants the same server.properties change on every accessible Minecraft server, use scope all_accessible_minecraft.",
"Do not assume a random word or short phrase is a server name.",
"If the user only says one or two ambiguous words, ask a brief clarifying question instead of calling tools.",
"If the user wants to create a new server, gather the required creation details: template, node, server name, and host port.",
"RAM, CPU, and storage limits are optional. Use them only when the user provided them or explicitly asks for limits.",
"If the user explicitly says to use defaults, you may use the template default port and leave optional resource limits unset.",
"If the user already provided a node, template, port, RAM, CPU, storage, or server name earlier in this chat, reuse it instead of asking again unless it is ambiguous.",
"For server creation, use list_templates and list_nodes when needed so you can offer concrete choices with node capacity and port information.",
"When the user asks to create a server but has not chosen a node or template yet, ask a short direct question listing the best available options.",
"For provisioning, never reply with generic phrases like 'I need more detail' or 'tell me more'. Name the exact missing field instead.",
"If the user already gave enough information to create the server, call create_server immediately.",
"If the user replies with a short follow-up like 'yes', 'go ahead', a port number, a node name, or a resource value, use the earlier provisioning context instead of restarting the flow.",
"Do not call create_server until you have enough information to create the server correctly.",
"If the user also asked for plugins during server creation, remember that request and install the plugins after the server exists.",
"Use install_plugin for Minecraft plugin requests. Prefer the server's known fork or version when available, otherwise use the latest compatible plugin build.",
"Never delete a server immediately from chat. Use request_delete_server first so the browser can show a confirmation modal with a security verification, and wait for the user's confirmation there.",
"The delete confirmation is completed by the admin in the browser modal, including any password or 2FA verification it asks for. Never ask for a password or 2FA code in chat and never claim a delete succeeded before the modal flow reports it.",
"You can assist any accessible server regardless of docker image or template for file and power actions, as long as the user has permission.",
"If the user wants every accessible server started, stopped, restarted, or killed, use power_accessible_servers instead of calling power_server repeatedly.",
"If a named server request does not resolve immediately, use the available server tools and closest candidates before saying you cannot see that server.",
"For browser-queued read actions like diagnosis or busiest node checks, say checking now, not done.",
"For browser-queued actions, say starting, stopping, restarting, killing, or opening now. Do not claim the final action already completed before the browser runs it.",
"If a server name is unclear, use the available tools to discover or confirm the correct server before taking action.",
`Current authenticated user: ${String(userEmail || "unknown").trim() || "unknown"}.`,
].join(" ");
}
function parseToolArguments(raw) {
if (!raw) return {};
if (typeof raw === "object") return raw;
try {
const parsed = JSON.parse(String(raw));
return parsed && typeof parsed === "object" ? parsed : {};
} catch {
return {};
}
}
function buildMaskedError(message, extra = {}) {
return Object.assign({ ok: false, error: message }, extra);
}
function buildSuccess(data) {
return Object.assign({ ok: true }, data);
}
function normalizeRelativePath(input) {
return String(input || "").replace(/\0/g, "").trim();
}
// adpanel:relay-helper-consolidation — safeJoinUnix is now the shared
// services/node-fs-relay.js implementation (panel style), re-bound above. ONE
// flagged hardening rides along: the former local copy STRIPPED NUL bytes and
// continued; the shared union REJECTS any NUL/control-bearing path, so the
// assistant's file tools now refuse those inputs with the panel traversal
// message instead of forwarding a path every panel route then refuses to
// operate on — fail-closed, the same guard class the panel and relay surfaces
// adopted in the relay consolidation. Traversal/absolute/control messages are
// unchanged ("Unix path traversal detected" / "Absolute path not allowed" /
// "Unsafe characters in path"), so surfaced error text only changes for
// NUL-bearing paths.
// Issue 1 port (now the shared services/node-fs-relay.js
// isServerRootResolvedPath, re-bound above): true when a safeJoinUnix result
// IS the server root. normalizeRelativePath accepts "." and safeJoinUnix
// resolves it (and "a/..", "./") back to the base dir, so the delete/rename
// tools must compare the RESOLVED path against the normalized base —
// whole-server destruction stays reserved for the dedicated admin
// server-delete flow, exactly like every other delete path in the panel. The
// shared copy's 3-form superset (normalized base, stripped base, stripped
// base + "/") classifies every posix.join output this module can produce
// identically to the former local single-compare form.
function truncateText(text, limit = FILE_PREVIEW_LIMIT) {
const value = String(text ?? "");
if (value.length <= limit) {
return { content: value, truncated: false, originalLength: value.length };
}
return {
content: `${value.slice(0, limit)}\n\n[Truncated by ADPanel Assistant]`,
truncated: true,
originalLength: value.length,
};
}
// decodeNodeFileReadContent is the shared services/node-fs-relay.js copy
// (re-bound above; byte-identical semantics to the twin this module used to
// carry — this module cannot import index.js, and now does not need to
// duplicate it either). The daemon's "utf8" read mode lossily replaces
// non-UTF-8 bytes with U+FFFD, so reads request base64 and validate the bytes
// strictly: a binary file is reported as binary instead of being served as
// mangled text the write_file tool could save back over the original; empty
// files decode to "".
function coerceNumber(value) {
if (value === undefined || value === null || value === "") return null;
const num = Number(value);
return Number.isFinite(num) ? num : null;
}
function normalizeLooseText(value) {
return String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
}
function compareMcVersionsDesc(left, right) {
const leftParts = String(left || "").split(".").map((part) => parseInt(part, 10) || 0);
const rightParts = String(right || "").split(".").map((part) => parseInt(part, 10) || 0);
const maxLength = Math.max(leftParts.length, rightParts.length);
for (let index = 0; index < maxLength; index += 1) {
const delta = (rightParts[index] || 0) - (leftParts[index] || 0);
if (delta !== 0) return delta;
}
return 0;
}
function normalizePluginLoader(value) {
const normalized = String(value || "").trim().toLowerCase();
if (!normalized) return "";
if (normalized === "bungee" || normalized === "bungeecord") return "bungeecord";
if (normalized === "waterfall" || normalized === "velocity") return normalized;
if (normalized === "paper" || normalized === "purpur" || normalized === "spigot" || normalized === "bukkit") return normalized;
if (normalized === "neo" || normalized === "neo-forge" || normalized === "neoforge") return "neoforge";
if (normalized === "forge" || normalized === "fabric" || normalized === "quilt") return normalized;
return normalized;
}
function inferServerPluginLoader(entry) {
const candidates = [
entry?.mcFork,
entry?.runtime?.providerId,
entry?.runtime?.versionId,
entry?.runtime?.command,
entry?.runtime?.startupCommand,
entry?.startupCommand,
entry?.template,
].map((value) => String(value || "").toLowerCase());
for (const loader of MODRINTH_PLUGIN_LOADERS) {
if (candidates.some((candidate) => candidate.includes(loader))) {
return loader;
}
}
if (String(entry?.template || "").trim().toLowerCase() === "minecraft") {
return normalizePluginLoader(entry?.mcFork || "paper");
}
return "";
}
function inferServerMinecraftVersion(entry) {
return String(entry?.mcVersion || "").trim();
}
function scoreModrinthHit(hit, query) {
const queryText = normalizeLooseText(query);
const slug = normalizeLooseText(hit?.slug);
const title = normalizeLooseText(hit?.title);
let score = 0;
if (slug === queryText || title === queryText) score += 12;
if (slug.replace(/\s+/g, "") === queryText.replace(/\s+/g, "")) score += 10;
if (title.includes(queryText)) score += 5;
if (slug.includes(queryText)) score += 4;
score += Math.min(Number(hit?.downloads || 0), 500000) / 500000;
if (hit?.featured) score += 1;
return score;
}
async function fetchJsonOrError(deps, url) {
const response = await deps.httpRequestJson(url, "GET", {
"Accept": "application/json",
"User-Agent": "ADPanel-Assistant",
}, null, 20_000);
if (response.status !== 200 || !response.json) {
return { error: `Request failed (${response.status || 0}).` };
}
return { json: response.json };
}
async function resolveModrinthProject(deps, pluginName) {
const query = String(pluginName || "").trim();
if (!query) {
return { error: "A plugin name is required." };
}
const facets = encodeURIComponent('[["project_type:plugin"]]');
const url = `${MODRINTH_API_BASE}/search?limit=8&query=${encodeURIComponent(query)}&facets=${facets}`;
const { json, error } = await fetchJsonOrError(deps, url);
if (error) return { error: `Modrinth search failed. ${error}` };
const hits = Array.isArray(json?.hits) ? json.hits : [];
if (!hits.length) {
return { error: `No Modrinth plugin matched "${query}".` };
}
const sorted = hits
.slice()
.sort((left, right) => scoreModrinthHit(right, query) - scoreModrinthHit(left, query));
const best = sorted[0];
if (!best?.project_id) {
return { error: `No Modrinth plugin matched "${query}".` };
}
return {
project: {
id: best.project_id,
slug: best.slug || "",
title: best.title || best.slug || query,
description: best.description || "",
},
};
}
async function fetchModrinthProjectVersions(deps, projectId) {
const url = `${MODRINTH_API_BASE}/project/${encodeURIComponent(projectId)}/version`;
const { json, error } = await fetchJsonOrError(deps, url);
if (error) return { error: `Failed to load plugin versions. ${error}` };
const versions = Array.isArray(json) ? json : [];
return { versions };
}
function chooseBestPluginVersion(versions, { platform, gameVersion }) {
const normalizedPlatform = normalizePluginLoader(platform);
const normalizedVersion = String(gameVersion || "").trim();
const candidates = (Array.isArray(versions) ? versions : [])
.filter((entry) => Array.isArray(entry?.files) && entry.files.some((file) => file?.url))
.map((entry) => {
const loaders = Array.isArray(entry?.loaders) ? entry.loaders.map(normalizePluginLoader).filter(Boolean) : [];
const gameVersions = Array.isArray(entry?.game_versions) ? entry.game_versions.map((value) => String(value || "").trim()).filter(Boolean) : [];
let score = 0;
if (normalizedPlatform && loaders.includes(normalizedPlatform)) score += 8;
if (!normalizedPlatform && loaders.some((loader) => MODRINTH_PLUGIN_LOADERS.includes(loader))) score += 2;
if (normalizedVersion && gameVersions.includes(normalizedVersion)) score += 8;
if (!normalizedVersion && gameVersions.length) score += 1;
if (entry?.featured) score += 1;
return { entry, loaders, gameVersions, score };
})
.filter((item) => {
if (normalizedPlatform && !item.loaders.includes(normalizedPlatform)) return false;
if (normalizedVersion && !item.gameVersions.includes(normalizedVersion)) return false;
return true;
});
const pool = candidates.length ? candidates : (Array.isArray(versions) ? versions : [])
.filter((entry) => Array.isArray(entry?.files) && entry.files.some((file) => file?.url))
.map((entry) => ({
entry,
loaders: Array.isArray(entry?.loaders) ? entry.loaders.map(normalizePluginLoader).filter(Boolean) : [],
gameVersions: Array.isArray(entry?.game_versions) ? entry.game_versions.map((value) => String(value || "").trim()).filter(Boolean) : [],
score: 0,
}));
if (!pool.length) return null;
pool.sort((left, right) => {
if (right.score !== left.score) return right.score - left.score;
const versionCompare = compareMcVersionsDesc(left.gameVersions[0] || "", right.gameVersions[0] || "");
if (versionCompare !== 0) return versionCompare;
return new Date(right.entry?.date_published || 0).getTime() - new Date(left.entry?.date_published || 0).getTime();
});
return pool[0];
}
function getServerAliases(entry) {
const aliases = new Set();
for (const value of [
entry?.name,
entry?.displayName,
entry?.id,
entry?.bot,
entry?.legacyId,
]) {
const cleaned = String(value || "").trim();
if (cleaned) {
aliases.add(cleaned);
const spaced = cleaned.replace(/[_./-]+/g, " ").replace(/\s+/g, " ").trim();
if (spaced) aliases.add(spaced);
}
}
return Array.from(aliases);
}
function stripLookupDiacritics(value) {
return String(value || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "");
}
function normalizeLookupPhrase(value) {
return stripLookupDiacritics(value)
.toLowerCase()
.replace(/[`"'“”‘’]/g, " ")
.replace(/[_./-]+/g, " ")
.replace(/[^a-z0-9 ]+/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function compactLookupPhrase(value) {
return normalizeLookupPhrase(value).replace(/\s+/g, "");
}
function stripServerLookupFiller(value) {
return normalizeLookupPhrase(value)
.replace(/\b(?:the|my|our|please|pls|now|right|right now|server|servers|serverul|serverele|servere|srv|named|called|bot|instance|start|run|boot|bring|spin|restart|reboot|stop|shutdown|shut|kill|terminate|turn|power|on|off|up|down|porneste|pornește|opreste|oprește|inchide|închide|reporneste|repornește|omoara|omoară|ucide|for|on|la|pe)\b/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function addLookupForms(set, value) {
const raw = String(value || "").trim().toLowerCase();
if (raw) set.add(raw);
const normalized = normalizeLookupPhrase(value);
if (normalized) set.add(normalized);
const compact = compactLookupPhrase(value);
if (compact) set.add(compact);
}
function buildRequestedServerForms(requestedServer) {
const forms = new Set();
const raw = String(requestedServer || "").trim();
if (!raw) return forms;
addLookupForms(forms, raw);
addLookupForms(forms, stripServerLookupFiller(raw));
const quoted = raw.match(/["'`“”]([^"'`“”]{1,120})["'`“”]/);
if (quoted) {
addLookupForms(forms, quoted[1]);
addLookupForms(forms, stripServerLookupFiller(quoted[1]));
}
const wrappedMatches = Array.from(raw.matchAll(/[\(\[]([^()\[\]]{1,120})[\)\]]/g));
for (const match of wrappedMatches) {
addLookupForms(forms, match[1]);
addLookupForms(forms, stripServerLookupFiller(match[1]));
}
return forms;
}
function scoreServerAliasMatch(alias, requestedForms) {
const aliasRaw = String(alias || "").trim().toLowerCase();
const aliasNormalized = normalizeLookupPhrase(alias);
const aliasCompact = compactLookupPhrase(alias);
const aliasTokens = new Set(aliasNormalized.split(" ").filter(Boolean));
let best = 0;
for (const requested of Array.from(requestedForms || [])) {
const needle = String(requested || "").trim().toLowerCase();
if (!needle) continue;
if (needle === aliasRaw || needle === aliasNormalized || needle === aliasCompact) {
return 1000;
}
const needleNormalized = normalizeLookupPhrase(needle);
const needleCompact = compactLookupPhrase(needle);
if (!needleNormalized && !needleCompact) continue;
if (needleCompact && aliasCompact && (aliasCompact.startsWith(needleCompact) || needleCompact.startsWith(aliasCompact))) {
best = Math.max(best, 260 - Math.abs(aliasCompact.length - needleCompact.length));
}
if (needleCompact && aliasCompact && (aliasCompact.includes(needleCompact) || needleCompact.includes(aliasCompact))) {
best = Math.max(best, 210 - Math.abs(aliasCompact.length - needleCompact.length));
}
if (needleNormalized && aliasNormalized && (aliasNormalized.startsWith(needleNormalized) || needleNormalized.startsWith(aliasNormalized))) {
best = Math.max(best, 180 - Math.abs(aliasNormalized.length - needleNormalized.length));
}
if (needleNormalized && aliasNormalized && (aliasNormalized.includes(needleNormalized) || needleNormalized.includes(aliasNormalized))) {
best = Math.max(best, 150 - Math.abs(aliasNormalized.length - needleNormalized.length));
}
const needleTokens = needleNormalized.split(" ").filter(Boolean);
const overlap = needleTokens.filter((token) => aliasTokens.has(token)).length;
if (overlap > 0) {
best = Math.max(best, overlap * 40 - Math.max(0, aliasTokens.size - overlap) * 4);
}
}
return best;
}
function getTemplateAliases(entry) {
const aliases = new Set();
for (const value of [entry?.id, entry?.name]) {
const cleaned = String(value || "").trim();
if (cleaned) aliases.add(cleaned);
}
return Array.from(aliases);
}
function resolveTemplateFromList(templates, requestedTemplate) {
const requested = String(requestedTemplate || "").trim().toLowerCase();
if (!requested) {
return { error: "A template is required." };
}
const exactMatches = templates.filter((entry) =>
getTemplateAliases(entry).some((alias) => alias.toLowerCase() === requested)
);
if (exactMatches.length === 1) {
return { entry: exactMatches[0] };
}
if (exactMatches.length > 1) {
return {
error: "Multiple templates matched that name.",
candidates: exactMatches.map((entry) => entry.id || entry.name),
};
}
const partialMatches = templates.filter((entry) =>
getTemplateAliases(entry).some((alias) => alias.toLowerCase().includes(requested))
);
if (partialMatches.length === 1) {
return { entry: partialMatches[0] };
}
if (partialMatches.length > 1) {
return {
error: "The template name is ambiguous.",
candidates: partialMatches.slice(0, 10).map((entry) => entry.id || entry.name),
};
}
return { error: "No template matched that name." };
}
function getNodeAliases(entry) {
const aliases = new Set();
for (const value of [entry?.id, entry?.uuid, entry?.name]) {
const cleaned = String(value || "").trim();
if (cleaned) aliases.add(cleaned);
}
return Array.from(aliases);
}
function resolveNodeFromList(nodes, requestedNode) {
const requested = String(requestedNode || "").trim().toLowerCase();
if (!requested) {
return { error: "A node is required." };
}
const exactMatches = nodes.filter((entry) =>
getNodeAliases(entry).some((alias) => alias.toLowerCase() === requested)
);
if (exactMatches.length === 1) {
return { entry: exactMatches[0] };
}
if (exactMatches.length > 1) {
return {
error: "Multiple nodes matched that name.",
candidates: exactMatches.map((entry) => entry.name || entry.id || entry.uuid),
};
}
const partialMatches = nodes.filter((entry) =>
getNodeAliases(entry).some((alias) => alias.toLowerCase().includes(requested))
);
if (partialMatches.length === 1) {
return { entry: partialMatches[0] };
}
if (partialMatches.length > 1) {
return {
error: "The node name is ambiguous.",
candidates: partialMatches.slice(0, 10).map((entry) => entry.name || entry.id || entry.uuid),
};
}
return { error: "No node matched that name." };
}
function getNodeResourceLimits(node) {
const buildConfig = node?.buildConfig && typeof node.buildConfig === "object" ? node.buildConfig : {};
const ramMb = coerceNumber(node?.ram_mb ?? buildConfig.ram_mb ?? buildConfig.ramMb) || 0;
const cpuCores = coerceNumber(node?.cpu_cores ?? buildConfig.cpu_cores ?? buildConfig.cpuCores) || 0;
const diskGb = coerceNumber(node?.disk_gb ?? buildConfig.disk_gb ?? buildConfig.diskGb) || 0;
return {
ramMb,
cpuCores,
diskGb,
diskMb: diskGb > 0 ? Math.round(diskGb * 1024) : 0,
};
}
function describeNodePorts(node) {
const ports = node?.ports && typeof node.ports === "object" ? node.ports : {};
if (ports.mode === "range" && coerceNumber(ports.start) > 0 && coerceNumber(ports.count) > 0) {
const start = Number(ports.start);
const end = start + Number(ports.count) - 1;
return {
mode: "range",
start,
end,
description: `${start}-${end}`,
};
}
if (ports.mode === "list" && Array.isArray(ports.ports) && ports.ports.length > 0) {
const normalizedPorts = ports.ports
.map((value) => Number(value))
.filter((value) => Number.isInteger(value) && value > 0)
.slice(0, 50);
return {
mode: "list",
ports: normalizedPorts,
description: normalizedPorts.slice(0, 12).join(", ") + (normalizedPorts.length > 12 ? "..." : ""),
};
}
return {
mode: "unknown",
description: "not declared",
};
}
async function createAccessibleServerCache(deps, userEmail) {
const list = (await deps.loadServersIndex()) || [];
const user = await deps.findUserByEmail(userEmail);
if (user?.admin) return list.filter(Boolean);
const accessList = (await deps.getAccessListForEmail(userEmail)) || [];
const lowered = new Set(accessList.map((item) => String(item || "").trim().toLowerCase()));
if (lowered.has("all")) return list.filter(Boolean);
return list.filter((entry) => entry?.name && lowered.has(String(entry.name).toLowerCase()));
}
// Candidate labels for ambiguous server matches. Plain "DisplayName (name)"
// strings: they only ever reach model context and reply text (never HTML),
// and the canonical server name stays visible so the model can retry with it.
function formatServerCandidate(entry) {
const name = String(entry?.name || "").trim();
const displayName = String(entry?.displayName || "").trim();
if (displayName && displayName.toLowerCase() !== name.toLowerCase()) {
return `${displayName} (${name})`;
}
return name;
}
// The shortest compact form of the request: the smallest reference the fuzzy
// match could have latched onto. Auto-selection is only allowed when even this
// shortest form carries enough text to identify a server, so vague queries
// ("s", "my server") can never silently resolve to one server.
function getShortestRequestedCompactForm(requestedForms) {
let shortest = "";
for (const form of Array.from(requestedForms || [])) {
const compact = compactLookupPhrase(form);
if (!compact) continue;
if (!shortest || compact.length < shortest.length) {
shortest = compact;
}
}
return shortest;
}
function resolveServerFromList(accessibleServers, requestedServer) {
const requested = String(requestedServer || "").trim();
if (!requested) {
return { error: "A server name is required." };
}
const requestedForms = buildRequestedServerForms(requested);
const scoredEntries = accessibleServers
.filter(Boolean)
.map((entry) => {
const aliases = getServerAliases(entry);
const score = aliases.reduce((best, alias) => Math.max(best, scoreServerAliasMatch(alias, requestedForms)), 0);
return { entry, score };
});
const exactMatches = scoredEntries.filter((item) => item.score >= 1000).map((item) => item.entry);
if (exactMatches.length === 1) {
return { entry: exactMatches[0] };
}
if (exactMatches.length > 1) {
return {
error: "Multiple servers matched that name.",
candidates: exactMatches.slice(0, 5).map((entry) => formatServerCandidate(entry)),
};
}
const partialMatches = scoredEntries
.filter((item) => item.score >= 120)
.sort((left, right) => right.score - left.score);
// Auto-select a fuzzy match only when it is confident: clearly strong (a
// compact prefix/substring hit on a specific-enough query) and uniquely best
// (a clear margin over the runner-up). Weak or prefix-only hits on vague
// queries, and close calls, return the top candidates so the model asks the
// user which server they meant — silently resolving a vague name can act on
// the wrong accessible server.
const topMatch = partialMatches[0];
const runnerUp = partialMatches[1];
const isConfident =
topMatch &&
topMatch.score >= SERVER_CONFIDENT_MATCH_SCORE &&
getShortestRequestedCompactForm(requestedForms).length >= SERVER_MIN_CONFIDENT_QUERY_LENGTH &&
(!runnerUp || topMatch.score >= runnerUp.score + SERVER_CONFIDENT_MATCH_MARGIN);
if (topMatch && isConfident) {
return { entry: topMatch.entry };
}
if (partialMatches.length > 0) {
return {
error: "The server name is ambiguous.",
candidates: partialMatches.slice(0, 5).map((item) => formatServerCandidate(item.entry)),
};
}
const candidates = scoredEntries
.filter((item) => item.score > 0)
.sort((left, right) => right.score - left.score)
.slice(0, 5)
.map((item) => formatServerCandidate(item.entry));
return {
error: "No accessible server matched that name.",
candidates,
};
}
function normalizePowerAction(value) {
const action = String(value || "").trim().toLowerCase();
return ["start", "stop", "restart", "kill"].includes(action) ? action : "";
}
function normalizeAssistantMetric(value) {
const metric = String(value || "").trim().toLowerCase();
return ["balanced", "cpu", "memory", "disk"].includes(metric) ? metric : "balanced";
}
function normalizeAssistantMetricList(value) {
const rawList = Array.isArray(value) ? value : [value];
const seen = new Set();
const metrics = [];
rawList.forEach((entry) => {
const metric = normalizeAssistantMetric(entry);
if (metric === "balanced" || seen.has(metric)) return;
seen.add(metric);
metrics.push(metric);
});
return metrics;
}
function normalizeServerPropertyKey(value) {
const key = String(value || "").trim();
if (!key) return "";
return /^[A-Za-z0-9._-]+$/.test(key) ? key : "";
}
function getEntryDisplayName(entry) {
return String(entry?.displayName || entry?.name || "").trim() || "that server";
}
function getNormalizedEntryTemplate(deps, entry) {
if (typeof deps?.normalizeTemplateId === "function") {
return String(deps.normalizeTemplateId(entry?.template) || "").trim().toLowerCase();
}
return String(entry?.template || "").trim().toLowerCase();
}
function isMinecraftServerEntry(deps, entry) {
const template = getNormalizedEntryTemplate(deps, entry);
if (template === "minecraft") return true;
const mcFork = String(entry?.mcFork || "").trim();
const mcVersion = String(entry?.mcVersion || "").trim();
const startFile = String(entry?.start || "").trim().toLowerCase();
const image = String(entry?.runtime?.image || entry?.docker?.image || "").trim().toLowerCase();
return !!(
mcFork ||
mcVersion ||
startFile === "server.jar" ||
image.includes("minecraft")
);
}
async function collectFileTargets(deps, entries, userEmail, requiredPerms = ["files_read", "files_create"]) {
const targets = [];
const skipped = [];
for (const entry of Array.isArray(entries) ? entries : []) {
if (!entry?.name) continue;
const displayName = getEntryDisplayName(entry);
if (!entry.nodeId) {
skipped.push({
server: entry.name,
displayName,
reason: "not_attached_to_node",
message: `${displayName} is not attached to a node.`,
});
continue;
}
// Same freeze the single-server resolver enforces: batch scopes must skip
// suspended servers with a clean reason instead of queueing a browser
// action that will bounce off the route-level 423.
if (entry.suspended) {
skipped.push({
server: entry.name,
displayName,
reason: "server_suspended",
message: `${displayName} is suspended.`,
});
continue;
}
const perms = await deps.getEffectivePermsForUserOnServer(userEmail, entry.name);
const missingPerm = requiredPerms.find((perm) => !perms?.[perm]);
if (missingPerm) {
skipped.push({
server: entry.name,
displayName,
reason: "permission_denied",
permission: missingPerm,
message: `You do not have permission to edit files on ${displayName}.`,
});
continue;
}
targets.push({
server: entry.name,
displayName,
template: getNormalizedEntryTemplate(deps, entry) || null,
});
}
return { targets, skipped, requiredPerms };
}
// adpanel:proxy-create-race (review fix, assistant port) — claim-row data
// source for the canonical ownership guard on the create_server tool path
// (services/server-create.js deleteOwnOrphanServerOnNodeForCreate): the tool
// has no SQL access, so readClaimRows is built over the injected servers-index
// readers — deliberately NOT dbQuery, the tool's guard data source stays the
// reader chain — preferring the freshest deleting-inclusive reader first:
// strictly dominant for a destructive-action guard (fresher AND deleting-
// inclusive), it closes the stale-cache window where a cached read predating
// another writer's committed row could let the compensating DELETE run into
// the winner's live server, while the deleting-inclusive-before-deleting-
// exclusive sub-ordering the destructive-action guards require stays behind
// it.
// adpanel:deleting-visibility — this guard gates a daemon DELETE, so it must
// see exactly what the shared ownership guard's live claim query
// (services/server-create.js deleteOwnOrphanServerOnNodeForCreate) sees,
// including a teardown-in-flight
// row. That was a deliberate behavior change when it landed: a status=
// 'deleting' row claiming the name on THIS node previously read as
// "unclaimed" (the deleting-excluding loadServersIndex(Fresh) fallbacks) and
// let the compensating DELETE run into an in-progress teardown; with the
// subscribe reader it WITHHOLDS (fail-closed, same convention as the HTTP
// guards). The older readers keep the guard runnable for hosts wired before
// this dep existed.
function createServerCreateCompensationDeps(deps) {
return {
readClaimRows: async (needle) => {
const readServersIndex = (typeof deps.loadServersIndexForSubscribeFresh === "function"
? deps.loadServersIndexForSubscribeFresh
: null)
// Deleting-inclusive cached read ranks AHEAD of the deleting-exclusive
// live read: on a legacy wiring without the fresh subscribe dep, a
// possibly-stale deleting row must still WITHHOLD the compensating
// delete (fail-closed) rather than vanish from a live read that
// filters status != 'deleting'.
|| (typeof deps.loadServersIndexForSubscribe === "function"
? deps.loadServersIndexForSubscribe
: null)
|| (typeof deps.loadServersIndexFresh === "function"
? deps.loadServersIndexFresh
: null)
|| (typeof deps.loadServersIndex === "function" ? deps.loadServersIndex : null);
if (!readServersIndex) {
// Fail closed: with no reader wired the guard cannot verify ownership
// and must delete nothing. The tag routes the tool's exact "no
// servers-index reader dep is wired" WITHHOLD line in
// logCreateServerCompensationOutcome; the canonical guard deletes
// nothing on a failed read either way.
const unwired = new Error("no servers-index reader dep is wired");
unwired.noServersIndexReaderDep = true;
throw unwired;
}
const existingRows = await readServersIndex();
const requestedNameLower = String(needle || "").trim().toLowerCase();
return (Array.isArray(existingRows) ? existingRows : [])
// Entries matched case-insensitively over name/legacyId|legacy_id/bot
// — the same alias match the canonical guard's SQL applies on the
// panel/proxy paths (their dbQuery fallback).
.filter((row) => {
if (!row) return false;
const rowName = String(row.name || "").trim().toLowerCase();
const rowLegacy = String(row.legacyId ?? row.legacy_id ?? "").trim().toLowerCase();
const rowBot = String(row.bot || "").trim().toLowerCase();
return rowName === requestedNameLower || rowLegacy === requestedNameLower || rowBot === requestedNameLower;
})
// Map to the guard's {name, node_id, ip} row shape with EXACTLY the
// fields the former inline guard read (row.nodeId / row.ip) — no
// snake_case node_id fallback, which would widen claim detection.
.map((row) => ({ name: row.name, node_id: row.nodeId, ip: row.ip }));
},
deleteServerOnNode: (node, serverName) => deps.deleteServerOnNode(node, serverName),
};
}
// Compensation log routing for the create_server tool's ownership-guarded
// compensating delete: one line per guard outcome, byte-identical to the
// former inline guard's warns (log lines are not wire contracts, but each
// create path keeps its exact wording — see panelCommitLog in
// services/server-create.js). `reason` is the failure that triggered the
// compensation ("template deleted during create", "index commit failed", "no
// insertServerIndexEntryGuarded dep is wired"); a successful delete logs
// nothing. Missing-dep and missing-reader wiring gaps are tagged by
// createServerCreateCompensationDeps so they render their own lines instead
// of the read-failure one.
function logCreateServerCompensationOutcome(reason, name, outcome) {
if (!outcome || outcome.deleted) return;
if (outcome.withheld) {
console.warn(`[dashboard-assistant create_server] ${reason} and a committed index row claims "${name}" on this node — compensating delete WITHHELD because the daemon server may belong to another writer's live create; winner left intact`);
return;
}
if (outcome.error && outcome.error.noServersIndexReaderDep) {
console.warn(`[dashboard-assistant create_server] ${reason} and no servers-index reader dep is wired, so ownership of daemon server "${name}" cannot be verified — compensating delete WITHHELD, server may be orphaned on the node`);
return;
}
if (outcome.error && outcome.phase === "read") {
console.warn(`[dashboard-assistant create_server] ${reason} and the ownership re-read failed (${outcome.error?.message || outcome.error}) — compensating delete of "${name}" WITHHELD, server may be orphaned on the node`);
return;
}
if (outcome.error) {
console.warn(`[dashboard-assistant create_server] ${reason} and compensating delete of "${name}" failed — server is orphaned on the node:`, outcome.error?.message || outcome.error);
}
}
// The failure reason each commitCreatedServer compensate kind maps to — the
// exact strings the former inline calls passed to the compensating-delete
// closure (and which every compensation log line above prefixes).
const CREATE_SERVER_COMPENSATION_REASONS = {
not_wired: "no insertServerIndexEntryGuarded dep is wired",
template_deleted: "template deleted during create",
commit_failed: "index commit failed",
};
function createDashboardAssistantToolRunner(deps, options = {}) {
if (!deps || typeof deps !== "object") {
throw new Error("Dashboard assistant tool dependencies are required.");
}
// Mode enforcement must live in the executor: offering the model a reduced
// tool list is only a prompt hint, not a security boundary, so a restricted
// mode passes its allowlist here and runTool rejects anything else before
// any argument parsing or server work happens. null (or not Set-like)
// disables the gate so unrestricted mode keeps every tool.
const allowedToolNames = options.allowedToolNames && typeof options.allowedToolNames.has === "function"
? options.allowedToolNames
: null;
return async function runTool({ name, args, userEmail, userIp, clientActions }) {
const toolName = String(name || "").trim();
if (allowedToolNames && !allowedToolNames.has(toolName)) {
return buildMaskedError("That tool is not available right now.");
}
const parsedArgs = parseToolArguments(args);
const accessibleServers = await createAccessibleServerCache(deps, userEmail);
const resolveServerOrError = async (requestedServer, permKey = null) => {
const resolved = resolveServerFromList(accessibleServers, requestedServer);
if (!resolved.entry) {
return { error: buildMaskedError(resolved.error || "Server not found.", resolved.candidates ? { candidates: resolved.candidates } : {}) };
}
const entry = resolved.entry;
// Suspension gate (port of resolveBotToolServerOrError in index.js): the
// file tools below reach the node daemon directly via deps.nodeFsPost,
// so the resolver is the only place the panel-wide suspension freeze can
// be enforced on this path. Entries come from loadServersIndex/mapServerRow,
// which always carries `suspended`.
if (entry.suspended) {
return {
error: buildMaskedError(`${entry.displayName || entry.name} is suspended.`, { code: "server-suspended" }),
};
}
const perms = await deps.getEffectivePermsForUserOnServer(userEmail, entry.name);
if (permKey && !perms[permKey]) {
return {
error: buildMaskedError(`You do not have permission to ${permKey.replace(/_/g, " ")} on ${entry.name}.`),
};
}
return { entry, perms };
};
switch (toolName) {
case "list_templates": {
const templates = (typeof deps.loadTemplatesFile === "function" ? deps.loadTemplatesFile() : []) || [];
return buildSuccess({
templates: templates.slice(0, 100).map((entry) => ({
id: entry?.id || "",
name: entry?.name || entry?.id || "",
description: entry?.description || "",
defaultPort: entry?.defaultPort ?? null,
})),
});
}
case "list_nodes": {
const currentUser = await deps.findUserByEmail(userEmail);
if (!(currentUser && currentUser.admin)) {
return buildMaskedError("Only administrators can create servers on nodes.");
}
const nodes = (typeof deps.loadNodes === "function" ? await deps.loadNodes() : []) || [];
return buildSuccess({
nodes: nodes.slice(0, 100).map((entry) => ({
...getNodeResourceLimits(entry),
id: entry?.id || null,
uuid: entry?.uuid || null,
name: entry?.name || entry?.id || entry?.uuid || "",
address: entry?.address || null,
online: !!entry?.online,
apiPort: entry?.api_port ?? 8080,
portAllocation: describeNodePorts(entry),
})),
});
}
case "create_server": {
const currentUser = await deps.findUserByEmail(userEmail);
if (!(currentUser && currentUser.admin)) {
return buildMaskedError("Only administrators can create new servers.");
}
const rawName = String(parsedArgs.name || "").trim();
const name = typeof deps.sanitizeServerName === "function" ? deps.sanitizeServerName(rawName) : rawName;
if (!name) {
return buildMaskedError("A valid server name is required.");
}
// adpanel:node-storage-name — the two node-storage-form guards are
// the canonical serverNameGuardOutcome (services/server-create.js,
// ONE home with the main create route and the node proxy):
// sanitizeServerToken keeps names the node's own sanitizer (main.go
// sanitizeName, mirrored in sanitizeNodeStorageName) would trim to
// nothing — no storable directory name at all — and a name whose
// storage form differs from its token form (leading/trailing "_" or
// ".") is stored under a different name on the node than the panel
// looks for, so the whole Files tab 400s for that server forever.
// Refuse before any provisioning work. Runs AFTER the tool's own
// empty-name check above (which stays tool-side:
// deps.sanitizeServerName may fall back to the raw name); the tool's
// prose envelopes are the renderer's "tool" variant.
const nameGuard = serverCreateService.serverNameGuardOutcome(name);
if (nameGuard) {
return serverCreateService.renderServerCreateOutcome(nameGuard, "tool").envelope;
}
const rawDisplayName = String(parsedArgs.displayName || rawName || "").trim();
const displayName = typeof deps.sanitizeDisplayName === "function"
? (deps.sanitizeDisplayName(rawDisplayName) || name)
: (rawDisplayName || name);
const templates = (typeof deps.loadTemplatesFile === "function" ? deps.loadTemplatesFile() : []) || [];
const resolvedTemplate = resolveTemplateFromList(templates, parsedArgs.templateId);
if (!resolvedTemplate.entry) {
return buildMaskedError(
resolvedTemplate.error || "Template not found.",
resolvedTemplate.candidates ? { candidates: resolvedTemplate.candidates } : {}
);
}
const template = resolvedTemplate.entry;
const normalizedTemplateId = typeof deps.normalizeTemplateId === "function"
? deps.normalizeTemplateId(template.id || parsedArgs.templateId)
: String(template.id || parsedArgs.templateId || "").trim().toLowerCase();
const nodes = (typeof deps.loadNodes === "function" ? await deps.loadNodes() : []) || [];
const resolvedNode = resolveNodeFromList(nodes, parsedArgs.nodeId);
if (!resolvedNode.entry) {
return buildMaskedError(
resolvedNode.error || "Node not found.",
resolvedNode.candidates ? { candidates: resolvedNode.candidates } : {}
);
}
let node = resolvedNode.entry;
if (node?.online === false) {
return buildMaskedError("That node is offline right now.");
}
// adpanel:deleting-visibility (assistant port) — both pre-checks read
// through loadServersIndexForSubscribeFresh, the cache-bypassing twin
// of the subscribe snapshot that KEEPS status='deleting' rows: exactly
// the visibility findServer (the main create route's pre-check), the
// node proxy's panelServerNameConflict and the main route's
// storage-collision scan have in their live, status-filter-free
// queries. The old loadServersIndex read excluded 'deleting' rows, so
// a name claimed by a teardown-in-flight row was refused by both HTTP
// paths but accepted here — a doomed create that died at the guarded
// commit with confusing errors. The loadServersIndexFresh /
// loadServersIndex fallbacks keep the checks runnable (with the old
// deleting-excluding visibility) for hosts wired before this dep
// existed; behavior only widens when the new reader is present.
const readExistingServers =
(typeof deps.loadServersIndexForSubscribeFresh === "function" ? deps.loadServersIndexForSubscribeFresh : null)
|| (typeof deps.loadServersIndexForSubscribe === "function" ? deps.loadServersIndexForSubscribe : null)
|| (typeof deps.loadServersIndexFresh === "function" ? deps.loadServersIndexFresh : null)
|| (typeof deps.loadServersIndex === "function" ? deps.loadServersIndex : null);
if (readExistingServers) {
const existingServers = await readExistingServers();
const requestedNameLower = String(name || "").trim().toLowerCase();
// M4 (assistant port): the duplicate check must match the arbiters
// the commit relies on — servers.name is UNIQUE and findServer (the
// main route's pre-check) matches name/legacy_id/bot, so legacy-id
// collisions are refused here instead of surfacing later as an
// ER_DUP_ENTRY after the container already exists on the node.
// Parity note (adpanel:deleting-visibility): findServer and
// panelServerNameConflict carry NO status filter, so a
// status='deleting' row claiming the name refuses here too now that
// the read includes deleting rows — same server_name_exists
// semantics as the HTTP paths.
const conflictingServer = Array.isArray(existingServers)
? existingServers.find((entry) => {
if (!entry || !requestedNameLower) return false;
const canonical = String(entry.name || "").trim().toLowerCase();
const legacy = String(entry.legacyId ?? entry.legacy_id ?? "").trim().toLowerCase();
const technical = String(entry.bot || "").trim().toLowerCase();
return canonical === requestedNameLower || legacy === requestedNameLower || technical === requestedNameLower;
})
: null;
if (conflictingServer) {
return buildMaskedError("That server name is already in use.", {
detail: `The name "${name}" matches an existing server or technical alias.`,
});
}
// adpanel:node-storage-name — the node filesystem namespace is Go's
// sanitizeName, not the panel's sanitizeServerToken (Go Trim's "-_."
// from both ends and strips leading non-alphanumerics), so two panel
// names whose Go forms collide share one node directory, and the
// second server would silently land in (or wipe into) the first
// one's storage. Refuse NEW collisions here: compare this name's
// node-storage form against every alias (name/legacy_id/bot) of
// every other server already registered on THIS node — mirroring
// the main create route's scan.
// Parity note (adpanel:deleting-visibility): the route's scan SQL
// ("SELECT name, legacy_id, bot FROM servers WHERE node_id = ? OR
// node_id = ? OR LOWER(node_id) = ?") has NO status filter either,
// so teardown-in-flight rows participate on both sides — a deleting
// row whose storage form collides now refuses here, as it does on
// the HTTP path.
// adpanel:proxy-create-race (review fix) — case-insensitive on BOTH
// sides: MySQL compares node_id = ? case-insensitively under its
// default collation, so an exact-case JS Set would MISS a row whose
// stored node_id differs only in case from node.id/uuid and let a
// colliding create proceed onto that row's node directory.
const nodeIdSetLower = new Set(
[node.id, node.uuid].map((value) => String(value || "").trim().toLowerCase()).filter(Boolean)
);
const nodeNameLower = String(node.name || "").trim().toLowerCase();
const requestedStorageName = sanitizeNodeStorageName(name);
const collidingRow = Array.isArray(existingServers)
? existingServers.find((row) => {
if (!row) return false;
const rowNodeId = String(row.nodeId || "").trim().toLowerCase();
if (!rowNodeId) return false;
// Mirror the route's SQL filter: node_id = id OR node_id = uuid
// OR LOWER(node_id) = LOWER(name) — all case-insensitive. Rows
// on other nodes cannot collide with this node's storage.
const onThisNode = nodeIdSetLower.has(rowNodeId)
|| (!!nodeNameLower && rowNodeId === nodeNameLower);
if (!onThisNode) return false;
// Same-name rows are already refused by the duplicate check
// above (case-insensitively), so skip them; null aliases
// sanitize to "".
if (String(row.name || "").trim().toLowerCase() === requestedNameLower) return false;
const storageForms = [row.name, row.legacyId ?? row.legacy_id, row.bot]
.map((alias) => sanitizeNodeStorageName(alias))
.filter(Boolean);
return storageForms.includes(requestedStorageName);
})
: null;
if (requestedStorageName && collidingRow) {
const collidingName = String(collidingRow.name || "").trim()
|| String(collidingRow.legacyId ?? collidingRow.legacy_id ?? "").trim()
|| "unknown";
// The tool's collision sentence is byte-identical to the shared
// renderer's (verified before routing through it), so only the
// string rendering is shared — the JS detection over the reader
// chain above stays tool-side, and the envelope (code
// "server_name_exists") is unchanged.
return serverCreateService.renderServerCreateOutcome(
{ ok: false, code: "server_name_storage_collision", data: { collidingName, name } },
"tool"
).envelope;
}
}
let hostPortRaw = coerceNumber(parsedArgs.hostPort);
if (hostPortRaw == null && template.defaultPort != null) {
hostPortRaw = coerceNumber(template.defaultPort);
}
if (hostPortRaw == null) {
return buildMaskedError("A port is required for that server. Tell me which port to allocate, or explicitly say to use defaults if the template has one.");
}
if (!Number.isInteger(hostPortRaw) || hostPortRaw < 1 || hostPortRaw > 65535) {
return buildMaskedError("The port must be a whole number between 1 and 65535.");
}
const resolvedPort = hostPortRaw != null ? Number(hostPortRaw) : (coerceNumber(template.defaultPort) || 0);
if (resolvedPort > 0 && typeof deps.isPortInNodeAllocation === "function" && !deps.isPortInNodeAllocation(node, resolvedPort)) {
return buildMaskedError(`Port ${resolvedPort} is not in this node's allocated ports.`, {
allocation: describeNodePorts(node),
});
}
const inputResources = parsedArgs.resources && typeof parsedArgs.resources === "object" ? parsedArgs.resources : {};
const startFile = normalizedTemplateId === "minecraft"
? "server.jar"
: (normalizedTemplateId === "nodejs" || normalizedTemplateId === "discord-bot"
? "index.js"
: (normalizedTemplateId === "python" ? "main.py" : null));
// adpanel:F8 - normalize/validate the fork and version the same way
// the create endpoint does, so a chat-driven create fails here with a
// clear message instead of a 400 after the fact.
const mcFork = normalizedTemplateId === "minecraft"
? resolveMcFork(parsedArgs.mcFork)
: undefined;
const mcVersion = normalizedTemplateId === "minecraft"
? resolveMcVersion(parsedArgs.mcVersion)
: undefined;
if (normalizedTemplateId === "minecraft" && (mcFork === null || mcVersion === null)) {
return buildMaskedError(
`I couldn't use that Minecraft fork or version. Supported forks: ${SUPPORTED_MC_FORKS.join(", ")}. Versions look like 1.21.8, 1.21.8-pre1, or a snapshot such as 24w14a.`,
{ mcFork: parsedArgs.mcFork || null, mcVersion: parsedArgs.mcVersion || null }
);
}
const importUrl = parsedArgs.importUrl ? String(parsedArgs.importUrl).trim() : null;
if (importUrl) {
if (typeof deps.isValidArchiveUrl === "function" && !deps.isValidArchiveUrl(importUrl)) {
return buildMaskedError("The import URL must be http(s) and point to a supported archive file.");
}
if (typeof deps.assertSafeRemoteUrl === "function") {
try {
await deps.assertSafeRemoteUrl(importUrl);
} catch (error) {
return buildMaskedError("The import URL is not allowed.", {
detail: error?.message || String(error),
});
}
}
}
const resources = {};
if (inputResources.ramMb != null) resources.ramMb = parseInt(inputResources.ramMb, 10) || null;
if (inputResources.cpuCores != null) resources.cpuCores = parseFloat(inputResources.cpuCores) || null;
if (inputResources.storageMb != null) resources.storageMb = parseInt(inputResources.storageMb, 10) || null;
else if (inputResources.storageGb != null) resources.storageMb = (parseInt(inputResources.storageGb, 10) || 0) * 1024 || null;
// swapMb 0 is a legal value, so an unparseable swapMb is normalized to
// null explicitly instead of `|| null`, which would also swallow 0.
if (inputResources.swapMb != null) {
const swapMbParsed = parseInt(inputResources.swapMb, 10);
resources.swapMb = Number.isNaN(swapMbParsed) ? null : swapMbParsed;
}
// adpanel:backup-cap-daemon-enforced — the panel-side count-then-create
// checks (scheduler fire path, interactive relay) are a TOCTOU
// fast-fail; the daemon's backupsMax (checked under the per-server op
// lock over an untruncated ReadDir of ALL backup subdirs) is the
// authoritative bound, so when the request does not name one, the
// payload carries the resolved panel cap — never 0/undefined, which
// the daemon (`if backupsMax > 0`) reads as "no cap". An explicit
// request value (including 0 = deliberately no daemon cap) still
// passes through untouched.
// adpanel:backup-cap-parse-hardening — the parse/degrade lives in the
// ONE shared helper (utils/backup-cap.js): garbage/negative explicit
// values degrade to the panel cap, never to unlimited. This replaced
// the tool's former `parseInt(...) || 0` + post-hoc negative
// rejection: with the degrade-to-cap helper a negative value can no
// longer reach this point, so the rejection became unreachable and
// was dropped (consistent degrade-to-cap semantics across every
// backupsMax transmission site, pinned in
// tests/backup-cap-daemon-wiring.test.js).
resources.backupsMax = resolveBackupsMaxFromInput(inputResources.backupsMax);
if (inputResources.maxSchedules != null) resources.maxSchedules = parseInt(inputResources.maxSchedules, 10) || 0;
const nodeLimits = getNodeResourceLimits(node);
if (resources.ramMb != null && resources.ramMb <= 0) {
return buildMaskedError("RAM must be greater than 0 MB.");
}
if (resources.cpuCores != null && resources.cpuCores <= 0) {
return buildMaskedError("CPU cores must be greater than 0.");
}
if (resources.storageMb != null && resources.storageMb <= 0) {
return buildMaskedError("Storage must be greater than 0 MB.");
}
if (resources.swapMb != null && resources.swapMb < 0) {
return buildMaskedError("Swap must be greater than or equal to 0 MB.");
}
// (The former "Backups limit must be greater than or equal to 0."
// rejection was removed with adpanel:backup-cap-parse-hardening:
// resolveBackupsMaxFromInput can never yield a negative, so the
// check was unreachable dead code.)
if (resources.maxSchedules != null && resources.maxSchedules < 0) {
return buildMaskedError("Schedules limit must be greater than or equal to 0.");
}
if (nodeLimits.ramMb > 0 && resources.ramMb != null && resources.ramMb > nodeLimits.ramMb) {
return buildMaskedError(`RAM cannot exceed this node's limit (${nodeLimits.ramMb} MB).`);
}
if (nodeLimits.cpuCores > 0 && resources.cpuCores != null && resources.cpuCores > nodeLimits.cpuCores) {
return buildMaskedError(`CPU cannot exceed this node's limit (${nodeLimits.cpuCores} cores).`);
}
if (nodeLimits.diskMb > 0 && resources.storageMb != null && resources.storageMb > nodeLimits.diskMb) {
return buildMaskedError(`Storage cannot exceed this node's limit (${nodeLimits.diskMb} MB).`);
}
let sanitizedDocker = sanitizeDockerTemplatePayload(template.docker);
// adpanel:async-create-parity (assistant port) — mirror the main
// route's payload construction (index.js POST /api/servers/create).
// asyncSetup: true makes the daemon answer 200 right after its
// synchronous preflight (meta.setupStatus "queued") and run the jar
// download (30-min context), the importUrl archive extraction and the
// container start in a background goroutine. Without it the daemon
// runs ALL of that inside the one HTTP handler — far beyond
// createOnRemoteNode's 600 s client timeout — so the tool read a
// recoverable timeout, its retry re-POSTed into the still-running
// handler, and the failure path drove the compensating delete INTO
// the in-flight create's serverDir (orphan container, no panel row).
// importUrl stays in the payload: the background goroutines
// (finishMinecraftCreateSetup / finishCustomCreateSetup) consume
// req.ImportUrl, so imports remain daemon-side and asynchronous.
// Accepted residual window (the route's own): with asyncSetup, a
// commit-failure compensation can still overlap the just-started
// background setup for a few seconds — the ownership guard and the
// insert-only commit remain the backstops.
// adpanel:server-create-mutex (assistant port) — cross-process
// per-name lock shared with POST /api/servers/create (index.js
// injects the same acquireServerCreateLock, so an assistant create
// and an HTTP create of the same name serialize across pm2 workers
// instead of racing their node provision + index commit). tryAcquire
// is synchronous and fail-fast: contention answers a tool error
// instead of queueing, mirroring the route's 429
// "action-in-progress" shape. Release happens in the finally below
// on every early-return and throw path.
const releaseServerCreateLock = typeof deps.acquireServerCreateLock === "function"
? deps.acquireServerCreateLock(name)
: null;
if (typeof deps.acquireServerCreateLock === "function" && !releaseServerCreateLock) {
return buildMaskedError(`Server "${name}" is already being created. Please choose a different name or wait.`, {
code: "action-in-progress",
});
}
const createLocked = async () => {
const nodeId = node.id || node.uuid;
const fresh = typeof deps.findNodeByIdOrName === "function"
? await deps.findNodeByIdOrName(nodeId)
: (await deps.loadNodes()).find(entry => (entry.id || entry.uuid) === nodeId);
if (!fresh || (fresh.id || fresh.uuid) !== nodeId) return buildMaskedError("That node no longer exists.");
node = fresh;
if (typeof deps.findServerUsingNodePort === "function") {
const [requirement] = deps.dockerTemplateHostPortRequirements(sanitizedDocker, resolvedPort);
const portOutcome = requirement && await serverCreateService.checkServerCreatePort(deps, node, requirement, name);
if (portOutcome?.code === "port_not_in_allocation") {
return buildMaskedError(`Port ${resolvedPort} is not in this node's allocated ports.`, { allocation: describeNodePorts(node) });
}
if (portOutcome) {
const response = serverCreateService.renderServerCreateOutcome(portOutcome, "panel").body;
return buildMaskedError(response.error, { code: response.code });
}
} else if (typeof deps.isPortInNodeAllocation === "function" && !deps.isPortInNodeAllocation(node, resolvedPort)) {
return buildMaskedError(`Port ${resolvedPort} is not in this node's allocated ports.`, { allocation: describeNodePorts(node) });
}
const bind = serverCreateService.resolveServerCreateBindAddress(node, resolvedPort);
if (bind.error) {
const response = serverCreateService.renderServerCreateOutcome(bind.error, "panel").body;
return buildMaskedError(response.error, { code: response.code });
}
const nodeBindIP = bind.address;
if (nodeBindIP && sanitizedDocker) {
sanitizedDocker.bind_ip = nodeBindIP;
sanitizedDocker.host_ip = nodeBindIP;
}
const payload = {
name,
templateId: template.id || normalizedTemplateId,
mcFork,
mcVersion,
hostPort: hostPortRaw,
bind_ip: nodeBindIP || undefined,
host_ip: nodeBindIP || undefined,
docker: typeof deps.dockerConfigForNodeRequest === "function" ? deps.dockerConfigForNodeRequest(sanitizedDocker) : sanitizedDocker,
autoStart: true,
asyncSetup: true,
importUrl,
resources: Object.keys(resources).length > 0 ? resources : null,
};
// Compensation for a failed commit (M4, mirrors the main create
// route): once the daemon create below succeeds, the node holds a
// real container, so any later failure must remove it again or the
// node keeps an unmanageable orphan. A compensation that itself
// fails (or cannot run because the dep is missing) is logged loudly
// with the "orphaned on the node" marker, never swallowed.
// adpanel:proxy-create-race (review fix, assistant port) — the
// delete is ownership-aware like the node proxy's
// deleteOwnOrphanServerOnNode: this request's own commit never
// landed on any path that reaches here, so a committed index row
// claiming this name belongs to ANOTHER writer (a rename/transfer/
// import that interleaved with the slow daemon create — non-create
// writers do not take the per-name create lock). Deleting by name
// alone would destroy that writer's live container and directory,
// so the index is re-read and the delete is issued only when the
// name is unclaimed or claimed on a DIFFERENT node. Withheld on any
// ambiguity — a wrongly-issued DELETE is the destroy primitive this
// guard exists to prevent; a withheld cleanup leaves at worst an
// orphan for the admin. The guard itself is the canonical
// deleteOwnOrphanServerOnNodeForCreate (services/server-create.js,
// ONE home with the panel route and the node proxy — same withhold
// rules, including rows with no node_id/ip); this path feeds it its
// own data source (createServerCreateCompensationDeps: the
// deleting-row-inclusive reader chain, deliberately not SQL) and
// keeps its exact per-mode log lines via
// logCreateServerCompensationOutcome.
const deleteCreatedServerOnNode = async (reason) => {
if (typeof deps.deleteServerOnNode !== "function") {
console.warn(`[dashboard-assistant create_server] ${reason} and no deleteServerOnNode dep is wired, so the compensating delete of "${name}" cannot run — server is orphaned on the node`);
return;
}
const outcome = await serverCreateService.deleteOwnOrphanServerOnNodeForCreate(
createServerCreateCompensationDeps(deps),
node,
name
);
logCreateServerCompensationOutcome(reason, name, outcome);
};
let createResult = null;
try {
createResult = await deps.createOnRemoteNode(node, payload);
} catch (error) {
return buildMaskedError("Failed to create that server.", {
detail: error?.message || String(error),
});
}
const technicalServerName = extractTechnicalServerNameFromNodeCreateResult(createResult, name) || name;
let savedPort = null;
if (hostPortRaw != null) {
savedPort = typeof deps.clampPort === "function" ? deps.clampPort(hostPortRaw) : hostPortRaw;
} else if (template.defaultPort) {
savedPort = typeof deps.clampPort === "function" ? deps.clampPort(template.defaultPort) : template.defaultPort;
} else if (normalizedTemplateId === "minecraft") {
savedPort = 25565;
} else if (normalizedTemplateId === "nodejs" || normalizedTemplateId === "discord-bot") {
savedPort = 3000;
}
const serverEntry = {
name,
displayName,
bot: technicalServerName && technicalServerName !== name ? technicalServerName : null,
template: template.id || normalizedTemplateId,
mcFork: normalizedTemplateId === "minecraft" ? mcFork : undefined,
mcVersion: normalizedTemplateId === "minecraft" ? mcVersion : undefined,
start: normalizedTemplateId === "minecraft"
? "server.jar"
: (normalizedTemplateId === "nodejs" || normalizedTemplateId === "discord-bot"
? "index.js"
: (normalizedTemplateId === "python" ? "main.py" : null)),
nodeId: node.uuid || node.id || node.name,
ip: nodeBindIP || node.address || null,
bind_ip: nodeBindIP || undefined,
host_ip: nodeBindIP || undefined,
// adpanel:async-create-parity (assistant port) — encode the async
// create exactly like the main route's serverEntry (index.js) and
// the node proxy's committed entry (nodes.js): "installing" while
// the daemon's background setup runs, "error" when it already
// reported failed, setupStatus from the daemon meta (default
// "queued"). A non-async 200 (older daemon — asyncSetup pruned by
// httpRequestJsonPruningUnknownFields) commits the old shape.
status: createResult?.asyncSetup
? (String(createResult?.meta?.setupStatus || "").toLowerCase() === "failed" ? "error" : "installing")
: undefined,
setupStatus: createResult?.asyncSetup ? (createResult?.meta?.setupStatus || "queued") : undefined,
};
if (savedPort != null) serverEntry.port = savedPort;
if (createResult?.meta?.setupMessage) serverEntry.setupMessage = createResult.meta.setupMessage;
if (Object.keys(resources).length > 0) serverEntry.resources = resources;
if (sanitizedDocker) serverEntry.docker = sanitizedDocker;
if (sanitizedDocker) {
serverEntry.runtime = {
image: sanitizedDocker.image,
tag: sanitizedDocker.tag,
command: sanitizedDocker.command,
volumes: sanitizedDocker.volumes,
env: sanitizedDocker.env,
ports: sanitizedDocker.ports,
portProtocols: sanitizedDocker.portProtocols,
};
}
// M4 (assistant port) — insert-only commit. The old commit went
// through deps.upsertServerIndexEntry (ON DUPLICATE KEY UPDATE), so
// a same-name create that raced this one across pm2 workers — the
// window neither the per-name lock nor the pre-checks above can
// fully close — silently repointed the other server's index row and
// orphaned its container. insertServerIndexEntryGuarded (same
// writer the main route and the node proxy commit through) INSERTs
// instead — a duplicate surfaces as ER_DUP_ENTRY rather than
// overwriting — and re-checks the template under the same
// "templates-write" key the template DELETE route holds. The full
// choreography — template-deleted and commit-failure compensation
// through the ownership-guarded delete above, ER_DUP_ENTRY mapping
// and the failure envelopes — is the shared commitCreatedServer
// (services/server-create.js); the compensate hook keeps this
// path's mode-aware compensation lines in deleteCreatedServerOnNode
// (the panel/proxy builder log config cannot express them without
// duplicating the strings), and the "tool" renderer below turns the
// shared outcome codes into this tool's byte-identical envelopes.
if (typeof deps.insertServerIndexEntryGuarded !== "function") {
// Fail closed: without the guarded writer there is no safe commit
// path (the old upsert fallback is exactly the regression this
// fix removes), so the just-created daemon server is compensated
// away instead of being left unregistered on the node. This
// wiring pre-check stays tool-side: the commit-unavailable
// envelope is tool-specific (the proxy renders
// index_commit_failed for the same condition).
await deleteCreatedServerOnNode("no insertServerIndexEntryGuarded dep is wired");
return buildMaskedError("The server was created on the node but could not be registered safely, so it was removed. Please try again.", {
code: "server_create_commit_unavailable",
});
}
const commitOutcome = await serverCreateService.commitCreatedServer(deps, {
entry: serverEntry,
name,
node,
templateName: template.name || template.id || normalizedTemplateId,
rethrowNonDup: false,
logTag: "[dashboard-assistant create_server]",
compensate: (kind) => deleteCreatedServerOnNode(CREATE_SERVER_COMPENSATION_REASONS[kind] || kind),
});
if (commitOutcome) {
return serverCreateService.renderServerCreateOutcome(commitOutcome, "tool").envelope;
}
// adpanel:assistant-activity-warn-only — the panel's own
// recordActivity call sites are warn-only (nodes.js, index.js): a
// logging failure must never fail the operation. This case has no
// catch below it, so a throw here would escape runTool entirely and
// fail the chat flow after the server was already created and
// committed.
if (typeof deps.recordActivity === "function") {
try {
deps.recordActivity(name, "server_create", {
template: template.id || normalizedTemplateId,
nodeId: node.uuid || node.id || node.name,
}, userEmail, userIp);
} catch (err) {
console.warn("[assistant-tools] Failed to record activity:", err?.message || err);
}
}
// adpanel:async-create-parity (assistant port) — with asyncSetup the
// daemon answered after its preflight only; the jar download,
// archive import and container start continue in its background
// goroutine. Say so instead of implying the server is already
// usable. A non-async 200 (older daemon — httpRequestJsonPruning
// UnknownFields pruned-and-logged the field) keeps the previous
// result shape unchanged.
const setupQueuedAsync = createResult?.asyncSetup === true;
// adpanel:async-create-parity (assistant port) — the daemon's
// synchronous prepare phase can already have persisted setupStatus
// "failed" before the 200 (updateSetupState runs before jsonWrite
// and the handler reloads meta before responding), and the
// serverEntry above commits "error" for exactly that case, so the
// result must not claim the setup is still running.
const setupFailedAtRespond = setupQueuedAsync
&& String(createResult?.meta?.setupStatus || "").toLowerCase() === "failed";
return buildSuccess({
created: true,
...(setupQueuedAsync ? {
setupQueued: !setupFailedAtRespond,
setupStatus: createResult?.meta?.setupStatus || "queued",
message: setupFailedAtRespond
? `Server "${displayName || name}" was created on node "${node.name || node.id || node.uuid}", but its setup failed before the background work could start${createResult?.meta?.setupMessage ? `: ${createResult.meta.setupMessage}` : "."}`
: `Server "${displayName || name}" was created on node "${node.name || node.id || node.uuid}". Its setup${importUrl ? " (including the archive import)" : ""} is running in the background on the node; the server will finish installing and appear online shortly.`,
} : {}),
server: {
name,
displayName,
template: template.id || normalizedTemplateId,
templateName: template.name || template.id || normalizedTemplateId,
nodeId: node.uuid || node.id || node.name,
nodeName: node.name || node.id || node.uuid,
port: savedPort,
},
});
};
try {
return await withKeyedLock(`node-ports:${node.id || node.uuid}`, createLocked);
} catch (error) {
return buildMaskedError("Failed to create that server.", { detail: error?.message || String(error) });
} finally {
// adpanel:server-create-mutex — release() is idempotent and
// token-checked (see acquireServerCreateLock in index.js): it only
// unlinks the lock file while this holder still owns it, so a lock
// stolen after a prolonged event-loop stall is left to its owner.
if (typeof releaseServerCreateLock === "function") releaseServerCreateLock();
}
}
case "list_servers": {
return buildSuccess({
servers: accessibleServers.slice(0, 100).map((entry) => ({
name: entry.name,
displayName: entry.displayName || entry.name,
status: entry.status || "unknown",
suspended: !!entry.suspended,
template: entry.template || "custom",
})),
});
}
case "inspect_server": {
const { entry, perms, error } = await resolveServerOrError(parsedArgs.server);
if (error) return error;
return buildSuccess({
server: {
name: entry.name,
displayName: entry.displayName || entry.name,
status: entry.status || "unknown",
template: entry.template || "custom",
nodeId: entry.nodeId || null,
ip: entry.ip || null,
port: entry.port ?? null,
mcFork: entry.mcFork || null,
mcVersion: entry.mcVersion || null,
permissions: perms,
},
});
}
case "get_busiest_node": {
const currentUser = await deps.findUserByEmail(userEmail);
if (!(currentUser && currentUser.admin)) {
return buildMaskedError("Only administrators can inspect node-wide load.");
}
const nodes = (typeof deps.loadNodes === "function" ? await deps.loadNodes() : []) || [];
if (!nodes.length) {
return buildMaskedError("No nodes are available.");
}
const metric = normalizeAssistantMetric(parsedArgs.metric);
const includeMetrics = normalizeAssistantMetricList(parsedArgs.includeMetrics);
if (Array.isArray(clientActions)) {
clientActions.push({
type: "assistant_find_busiest_node",
metric,
includeMetrics,
nodes: nodes.slice(0, 100).map((node) => ({
id: node?.id || node?.uuid || node?.name || "",
name: node?.name || node?.id || node?.uuid || "",
})).filter((node) => node.id),
});
}
return buildSuccess({
browserActionQueued: true,
metric,
includeMetrics,
nodeCount: nodes.length,
nodes: nodes.slice(0, 100).map((node) => ({
id: node?.id || node?.uuid || node?.name || "",
name: node?.name || node?.id || node?.uuid || "",
})).filter((node) => node.id),
});
}
case "get_busiest_server": {
if (!accessibleServers.length) {
return buildMaskedError("You do not have access to any servers.");
}
const metric = normalizeAssistantMetric(parsedArgs.metric);
const includeMetrics = normalizeAssistantMetricList(parsedArgs.includeMetrics);
const targets = accessibleServers
.filter((entry) => entry?.name && entry?.nodeId)
.slice(0, 200)
.map((entry) => ({
server: entry.name,
displayName: getEntryDisplayName(entry),
template: getNormalizedEntryTemplate(deps, entry) || null,
nodeId: entry.nodeId || null,
}));
if (!targets.length) {
return buildMaskedError("No accessible servers are attached to a node right now.");
}
if (Array.isArray(clientActions)) {
clientActions.push({
type: "assistant_find_busiest_server",
metric,
includeMetrics,
targets,
});
}
return buildSuccess({
browserActionQueued: true,
metric,
includeMetrics,
count: targets.length,
targets,
});
}
case "check_server_console": {
const query = String(parsedArgs.query || parsedArgs.server || "").trim();
const question = String(parsedArgs.question || "").trim();
if (!query) {
return buildMaskedError("A server name is required.");
}
if (Array.isArray(clientActions)) {
clientActions.push({
type: "assistant_check_server_console",
query,
question: question || query,
});
}
return buildSuccess({
browserActionQueued: true,
resolutionRequired: true,
query,
question: question || query,
});
}
case "check_server_limits": {
const query = String(parsedArgs.query || parsedArgs.server || "").trim();
const question = String(parsedArgs.question || "").trim();
const includeMetrics = normalizeAssistantMetricList(parsedArgs.includeMetrics);
if (!query) {
return buildMaskedError("A server name is required.");
}
if (Array.isArray(clientActions)) {
clientActions.push({
type: "assistant_check_server_limits",
query,
question: question || query,
includeMetrics,
});
}
return buildSuccess({
browserActionQueued: true,
resolutionRequired: true,
query,
question: question || query,
includeMetrics,
});
}
case "get_server_overview": {
const { entry, perms, error } = await resolveServerOrError(parsedArgs.server);
if (error) return error;
const question = String(parsedArgs.question || "").trim();
const templates = (typeof deps.loadTemplatesFile === "function" ? deps.loadTemplatesFile() : []) || [];
const templateId = getNormalizedEntryTemplate(deps, entry) || null;
const templateEntry = templateId
? templates.find((tpl) => String(tpl?.id || "").trim().toLowerCase() === templateId) || null
: null;
let nodeName = "";
const nodeId = String(entry.nodeId || "").trim();
if (nodeId && typeof deps.loadNodes === "function") {
try {
const nodes = (await deps.loadNodes()) || [];
const lowerNodeId = nodeId.toLowerCase();
const node = nodes.find((item) =>
[item?.id, item?.uuid, item?.name].some((value) => String(value || "").trim().toLowerCase() === lowerNodeId)
);
nodeName = String(node?.name || "").trim();
} catch {
}
}
const overview = {
server: entry.name,
displayName: getEntryDisplayName(entry),
lastKnownStatus: entry.status || "unknown",
template: {
id: templateId,
name: templateEntry?.name || null,
},
node: {
id: nodeId || null,
name: nodeName || null,
},
ip: entry.ip || null,
port: coerceNumber(entry.port) ?? null,
mcFork: entry.mcFork || null,
mcVersion: entry.mcVersion || null,
permissions: perms,
};
if (Array.isArray(clientActions)) {
clientActions.push({
type: "assistant_server_overview",
server: entry.name,
displayName: overview.displayName,
question: question || `Tell me about ${overview.displayName}.`,
overview,
});
}
return buildSuccess({
browserActionQueued: true,
question,
...overview,
});
}
case "diagnose_server": {
const { entry, perms, error } = await resolveServerOrError(parsedArgs.server);
if (error) return error;
if (Array.isArray(clientActions)) {
clientActions.push({
type: "assistant_diagnose_server",
server: entry.name,
displayName: getEntryDisplayName(entry),
template: getNormalizedEntryTemplate(deps, entry) || null,
permissions: perms,
});
}
return buildSuccess({
browserActionQueued: true,
server: entry.name,
displayName: getEntryDisplayName(entry),
template: getNormalizedEntryTemplate(deps, entry) || null,
permissions: perms,
});
}
case "update_minecraft_server_property": {
const property = normalizeServerPropertyKey(parsedArgs.property);
if (!property) {
return buildMaskedError("A valid server.properties key is required.");
}
if (parsedArgs.value === undefined || parsedArgs.value === null) {
return buildMaskedError("A value is required.");
}
// The browser applies this value to server.properties verbatim, so
// collapse control characters before it leaves the server: a lone
// "\r" (no "\n") is a line terminator to Java's Properties reader, so
// the class must be wider than /\r?\n/. A trailing ODD backslash run
// is the same differential in reverse -- Java continues the value
// onto the next file line -- so close the run by doubling it.
// Mirrors buildAssistantPropertiesLine() in
// public/js/dashboard-assistant.js.
const value = String(parsedArgs.value)
.replace(/[\u0000-\u001f\u007f]+/g, " ")
.trim()
.replace(/\\+$/, (run) => (run.length % 2 ? `${run}\\` : run));
const onlyIfCurrent = parsedArgs.onlyIfCurrent === undefined || parsedArgs.onlyIfCurrent === null
? ""
: String(parsedArgs.onlyIfCurrent).trim();
const restartAfter = !!parsedArgs.restartAfter;
const scope = String(parsedArgs.scope || "").trim().toLowerCase();
let candidateEntries = [];
if (scope === "single_server") {
const { entry, error } = await resolveServerOrError(parsedArgs.server);
if (error) return error;
candidateEntries = [entry];
} else if (scope === "all_accessible_minecraft") {
candidateEntries = accessibleServers.filter((entry) => isMinecraftServerEntry(deps, entry));
} else {
return buildMaskedError("Invalid Minecraft property update scope.");
}
if (!candidateEntries.length) {
return buildMaskedError(scope === "single_server" ? "That server could not be found." : "No accessible Minecraft servers were found.");
}
const nonMinecraft = candidateEntries.filter((entry) => !isMinecraftServerEntry(deps, entry));
if (nonMinecraft.length === candidateEntries.length) {
return buildMaskedError(scope === "single_server"
? `${getEntryDisplayName(candidateEntries[0])} is not a Minecraft server.`
: "No accessible Minecraft servers were found.");
}
const minecraftEntries = candidateEntries.filter((entry) => isMinecraftServerEntry(deps, entry));
const { targets, skipped } = await collectFileTargets(deps, minecraftEntries, userEmail, ["files_read", "files_create"]);
if (!targets.length) {
// A batch where every skip is suspension is not a permission story —
// say so in the headline (the skipped array always carries the truth).
const allSuspended = skipped.length > 0 && skipped.every((item) => item.reason === "server_suspended");
return buildMaskedError(
scope === "single_server"
? `You do not have permission to edit server.properties on ${getEntryDisplayName(minecraftEntries[0] || candidateEntries[0])}.`
: allSuspended
? "All matching Minecraft servers are suspended."
: "You do not have permission to edit server.properties on any matching Minecraft servers.",
skipped.length ? { skipped } : {}
);
}
if (Array.isArray(clientActions)) {
clientActions.push({
type: "assistant_update_minecraft_server_property",
property,
value,
scope,
path: "server.properties",
onlyIfCurrent: onlyIfCurrent || null,
restartAfter,
targets,
skipped,
});
}
return buildSuccess({
browserActionQueued: true,
property,
value,
scope,
path: "server.properties",
onlyIfCurrent: onlyIfCurrent || null,
restartAfter,
count: targets.length,
targets,
skipped,
});
}
case "install_plugin": {
const { entry, perms, error } = await resolveServerOrError(parsedArgs.server, "files_create");
if (error) return error;
if (!entry?.nodeId) {
return buildMaskedError("This server is not attached to a node.");
}
if (typeof deps.applyRemoteAssetToServer !== "function") {
return buildMaskedError("Plugin installation is not available here.");
}
const requestedPlugin = String(parsedArgs.pluginName || "").trim();
if (!requestedPlugin) {
return buildMaskedError("A plugin name is required.");
}
const projectResult = await resolveModrinthProject(deps, requestedPlugin);
if (!projectResult.project) {
return buildMaskedError(projectResult.error || "Plugin not found.");
}
const inferredPlatform = normalizePluginLoader(parsedArgs.platform || inferServerPluginLoader(entry) || "paper");
const inferredGameVersion = String(parsedArgs.gameVersion || inferServerMinecraftVersion(entry) || "").trim();
const versionResult = await fetchModrinthProjectVersions(deps, projectResult.project.id);
if (!versionResult.versions) {
return buildMaskedError(versionResult.error || "Failed to load plugin versions.");
}
const chosen = chooseBestPluginVersion(versionResult.versions, {
platform: inferredPlatform,
gameVersion: inferredGameVersion,
});
if (!chosen) {
return buildMaskedError(`No compatible Modrinth version was found for ${projectResult.project.title}.`, {
platform: inferredPlatform || null,
gameVersion: inferredGameVersion || null,
});
}
const file = chosen.entry.files.find((item) => item?.primary && item?.url) || chosen.entry.files.find((item) => item?.url);
if (!file?.url) {
return buildMaskedError("That plugin version does not provide a downloadable file.");
}
const pluginFileName = String(file.filename || file.url.split("/").pop() || `${projectResult.project.slug || "plugin"}.jar`).trim();
const applyResult = await deps.applyRemoteAssetToServer({
serverName: entry.name,
entry,
url: file.url,
destPath: `plugins/${pluginFileName}`,
});
if (!applyResult?.ok) {
return buildMaskedError("Failed to install that plugin.", {
detail: applyResult?.detail || applyResult?.error || "unknown-error",
});
}
// adpanel:assistant-activity-warn-only — a recordActivity failure must
// never fail the operation (the panel's own call sites are
// warn-only): this case has no catch below it, so a throw would
// escape runTool and fail the chat flow after the plugin already
// installed successfully.
if (typeof deps.recordActivity === "function") {
try {
deps.recordActivity(entry.name, "plugin_install", {
plugin: projectResult.project.slug || projectResult.project.title,
file: pluginFileName,
platform: inferredPlatform || null,
gameVersion: inferredGameVersion || null,
}, userEmail, userIp);
} catch (err) {
console.warn("[assistant-tools] Failed to record activity:", err?.message || err);
}
}
return buildSuccess({
server: entry.name,
plugin: {
name: projectResult.project.title,
slug: projectResult.project.slug || "",
loader: chosen.loaders[0] || inferredPlatform || null,
gameVersion: chosen.gameVersions[0] || inferredGameVersion || null,
versionId: chosen.entry.id || null,
fileName: pluginFileName,
},
destPath: `plugins/${pluginFileName}`,
permissions: perms,
});
}
case "request_delete_server": {
const currentUser = await deps.findUserByEmail(userEmail);
if (!(currentUser && currentUser.admin)) {
return buildMaskedError("Only administrators can delete servers.");
}
const resolved = resolveServerFromList(accessibleServers, parsedArgs.server);
if (!resolved.entry) {
// Never queue a confirm modal for an unresolved raw model string:
// only a resolved, accessible server id may reach the delete flow.
return buildMaskedError(
resolved.error || "Server not found.",
resolved.candidates ? { candidates: resolved.candidates } : {}
);
}
const serverName = resolved.entry.name;
if (Array.isArray(clientActions)) {
clientActions.push({
type: "confirm_delete_server",
server: serverName,
displayName: resolved.entry.displayName || serverName,
});
}
return buildSuccess({
server: serverName,
confirmationRequired: true,
});
}
case "list_files": {
const { entry, error } = await resolveServerOrError(parsedArgs.server, "files_read");
if (error) return error;
const ctx = await deps.resolveRemoteFsContext(entry.name);
if (!ctx.remote || !ctx.node) {
return buildMaskedError("This server is not attached to a node.");
}
try {
const fullPath = safeJoinUnix(ctx.baseDir, normalizeRelativePath(parsedArgs.path));
// adpanel:fs-scope - send the server scope so the node contains the
// operation inside this server's directory (symlink-safe).
const { status, json } = await deps.nodeFsPost(ctx.node, "/v1/fs/list", { path: fullPath, server: ctx.serverName }, 60_000);
if (status !== 200 || !json || !json.ok) {
return buildMaskedError("Failed to list files for that path.", {
detail: json?.error || `status ${status}`,
});
}
return buildSuccess({
server: entry.name,
path: normalizeRelativePath(parsedArgs.path),
entries: (Array.isArray(json.entries) ? json.entries : []).slice(0, 200).map((item) => ({
name: item?.name || "",
isDir: !!item?.isDir,
size: item?.size ?? null,
modifiedAt: item?.modifiedAt || item?.mtime || null,
})),
});
} catch (err) {
return buildMaskedError(err?.message || "Invalid path.");
}
}
case "read_file": {
const { entry, error } = await resolveServerOrError(parsedArgs.server, "files_read");
if (error) return error;
const filePath = normalizeRelativePath(parsedArgs.path);
if (!filePath) {
return buildMaskedError("A file path is required.");
}
const ctx = await deps.resolveRemoteFsContext(entry.name);
if (!ctx.remote || !ctx.node) {
return buildMaskedError("This server is not attached to a node.");
}
try {
const fullPath = safeJoinUnix(ctx.baseDir, filePath);
// adpanel:fs-scope - send the server scope so the node contains the
// operation inside this server's directory (symlink-safe).
// Base64 read (twin of the panel's /files/read route): the daemon's
// utf8 mode is already lossy for non-UTF-8 bytes, so the bytes are
// fetched as base64 and validated strictly below — the response cap
// is sized for the wire form (raw × 4/3 + envelope, see
// ASSISTANT_FS_READ_MAX_BYTES) so ~2 MiB of raw content still fits.
const { status, json, error: readError } = await deps.nodeFsPost(ctx.node, "/v1/fs/read", { path: fullPath, server: ctx.serverName, encoding: "base64" }, 120_000, { maxBytes: ASSISTANT_FS_READ_MAX_BYTES });
if (readError === "response too large") {
return buildMaskedError("That file is too large for the assistant to read. Use the file manager to view or download it instead.");
}
if (status !== 200 || !json || !json.ok) {
return buildMaskedError("Failed to read that file.", {
detail: json?.error || `status ${status}`,
});
}
const decoded = decodeNodeFileReadContent(typeof json.content === "string" ? json.content : "");
if (decoded.binary) {
return buildMaskedError("That file is binary and cannot be read as text. Use the file manager to upload or restore it instead.");
}
const preview = truncateText(decoded.text || "");
return buildSuccess({
server: entry.name,
path: filePath,
content: preview.content,
truncated: preview.truncated,
originalLength: preview.originalLength,
});
} catch (err) {
return buildMaskedError(err?.message || "Invalid path.");
}
}
case "write_file": {
// No permKey here: files_create (new files) and files_write
// (overwrite existing) are two separate capabilities, so the combined
// write capability is computed below, mirroring nodes.js
// resolveFsWriteMode. A user with neither is denied outright.
const { entry, perms, error } = await resolveServerOrError(parsedArgs.server);
if (error) return error;
const canCreate = !!perms?.files_create;
const canOverwrite = !!perms?.files_write;
if (!canCreate && !canOverwrite) {
return buildMaskedError(`You do not have permission to write files on ${entry.name}.`);
}
const filePath = normalizeRelativePath(parsedArgs.path);
if (!filePath) {
return buildMaskedError("A file path is required.");
}
const ctx = await deps.resolveRemoteFsContext(entry.name);
if (!ctx.remote || !ctx.node) {
return buildMaskedError("This server is not attached to a node.");
}
try {
const fullPath = safeJoinUnix(ctx.baseDir, filePath);
const desiredContent = String(parsedArgs.content ?? "");
if (Buffer.byteLength(desiredContent, "utf8") > ASSISTANT_FS_WRITE_MAX_BYTES) {
return buildMaskedError("That file is too large for the assistant to write. Use the file manager to upload files instead.");
}
// Both perms -> "" (legacy either), create-only -> "create",
// overwrite-only -> "update", same split as resolveFsWriteMode.
// Back-compat: older daemons ignore `mode` and keep the legacy
// either-behavior, so a create-only user keeps the (insecure)
// overwrite ability against not-yet-updated nodes until they upgrade.
const writeMode = canCreate && canOverwrite ? "" : canCreate ? "create" : "update";
// Issue 7 port: measure the serialized payload like index.js's
// nodeFsWritePayloadTooLarge (the daemon's MaxBytesReader sees the
// whole JSON envelope). The 1 MiB assistant cap above is tighter,
// so this is a backstop that keeps the friendly message if that cap
// is ever raised — the daemon would otherwise bounce the body as a
// generic failure.
const writePayload = {
path: fullPath,
server: ctx.serverName,
content: desiredContent,
encoding: "utf8",
mode: writeMode,
};
if (Buffer.byteLength(JSON.stringify(writePayload), "utf8") > NODE_FS_WRITE_BODY_LIMIT_BYTES_ASSISTANT) {
return buildMaskedError("That file exceeds the node's 10 MB write limit. Use the file manager to upload files instead.");
}
// Panel-side backstop for that back-compat gap: a create-only user
// (no files_write) must not be able to replace an existing file
// through an older daemon that ignores `mode`, so the panel is the
// only reliable enforcement point. Before forwarding, probe the
// parent directory with the same server-scoped, symlink-safe
// listing the list_files tool uses. Three outcomes:
// - Listing healthy (200 + ok + entries array): a taken name is
// rejected here; a free name proceeds to the write.
// - Parent definitively absent: the node's /v1/fs/list contract
// for a missing directory is 400 + ok:false +
// error:"not a directory" (handleFSList Lstats the path first
// and never answers 404), and /v1/fs/write creates parents, so
// creation in a new directory is legal and proceeds. That same
// 400 also covers a parent that is a file or a symlink; under
// a file nothing can be clobbered, but a symlinked parent
// still reaches the write unprobed (only the daemon's coarse
// 400 could tell them apart).
// - Anything else (network failure, other status, malformed
// body, ok:false without that marker): FAIL CLOSED for the
// create-only user with a retriable error and do not forward
// the write. This reverses the earlier defer-to-the-write
// behavior on purpose: the backstop exists precisely because
// legacy daemons ignore `mode`, so its own failure must not
// silently disable it — uncertainty never resolves in favor of
// a write that could clobber an existing file. The cost is
// availability only for create-only users against daemons
// whose listing is failing; on upgraded daemons the
// daemon-side mode enforcement remains the primary control.
// Known residual gap: probe-then-write is not atomic. Two
// concurrent create-only writes (or any other writer) can both
// observe a free name here and both reach a legacy daemon, where
// the second legacy write truncates the first; no panel-side
// post-write check can tell that clobber from a fresh create, so
// the window is accepted and only the daemon's O_EXCL open (the
// upgraded handleFSWrite "create" path) closes it atomically.
if (writeMode === "create") {
// Inner try/catch so a nodeFsPost throw lands in the fail-closed
// outcome above instead of the outer catch, which surfaces
// err?.message ("Invalid path.") as a path problem.
let probe = null;
try {
probe = await deps.nodeFsPost(ctx.node, "/v1/fs/list", { path: path.posix.dirname(fullPath), server: ctx.serverName }, 60_000);
} catch (probeErr) {
probe = null;
}
const entries = probe && probe.status === 200 && probe.json && probe.json.ok ? probe.json.entries : null;
if (Array.isArray(entries)) {
if (entries.some((item) => item && item.name === path.posix.basename(fullPath))) {
return buildMaskedError("That file already exists. Overwriting existing files requires the files_write permission.");
}
} else if (!(probe && probe.status === 400 && probe.json && probe.json.ok === false && probe.json.error === "not a directory")) {
return buildMaskedError("Could not verify that this file is new. Please try again in a moment.");
}
}
const { status, json } = await deps.nodeFsPost(
ctx.node,
"/v1/fs/write",
// adpanel:fs-scope - server scopes the write to this server's
// directory on the node; mode keeps the create/update split.
writePayload,
120_000
);
if (status !== 200 || !json || !json.ok) {
if (writeMode === "create" && status === 409) {
return buildMaskedError("That file already exists. Overwriting existing files requires the files_write permission.");
}
if (writeMode === "update" && status === 404 && json && json.existed === false) {
return buildMaskedError("That file does not exist. Creating new files requires the files_create permission.");
}
// Issue 7 port: the daemon's 400 "content too large
// (max 10MB)" must surface as the limit message, not a generic
// write failure.
if (status === 400 && typeof json?.error === "string" && json.error.includes(NODE_FS_WRITE_TOO_LARGE_MARKER_ASSISTANT)) {
return buildMaskedError("That file exceeds the node's 10 MB write limit. Use the file manager to upload files instead.");
}
return buildMaskedError("Failed to write that file.", {
detail: json?.error || `status ${status}`,
});
}
const verifyResult = await deps.nodeFsPost(
ctx.node,
"/v1/fs/read",
// adpanel:fs-scope - same server scope as the write above.
{ path: fullPath, server: ctx.serverName, encoding: "utf8" },
120_000,
{ maxBytes: ASSISTANT_FS_READ_MAX_BYTES }
);
if (verifyResult.status !== 200 || !verifyResult.json || !verifyResult.json.ok) {
return buildMaskedError("The file write could not be verified.", {
detail: verifyResult.json?.error || verifyResult.error || `status ${verifyResult.status}`,
});
}
if (String(verifyResult.json.content ?? "") !== desiredContent) {
return buildMaskedError("The file write could not be verified.");
}
// adpanel:assistant-activity-warn-only — a recordActivity failure
// must never fail the operation (the panel's own call sites are
// warn-only): a throw here lands in this case's buildMaskedError
// catch and reports a FAILED file edit after the write already
// succeeded and was verified.
if (typeof deps.recordActivity === "function") {
try {
deps.recordActivity(entry.name, "file_edit", { path: filePath }, userEmail, userIp);
} catch (err) {
console.warn("[assistant-tools] Failed to record activity:", err?.message || err);
}
}
return buildSuccess({ server: entry.name, path: filePath, written: true, verified: true });
} catch (err) {
return buildMaskedError(err?.message || "Invalid path.");
}
}
case "create_directory": {
const { entry, error } = await resolveServerOrError(parsedArgs.server, "files_create");
if (error) return error;
const dirPath = normalizeRelativePath(parsedArgs.path);
if (!dirPath) {
return buildMaskedError("A directory path is required.");
}
const ctx = await deps.resolveRemoteFsContext(entry.name);
if (!ctx.remote || !ctx.node) {
return buildMaskedError("This server is not attached to a node.");
}
try {
const fullPath = safeJoinUnix(ctx.baseDir, dirPath);
// Refuse server-root-resolving paths ("." and "a/../.." normalize
// back to the base dir): the .keep marker would land in the server
// root, the same stray-marker nit the other surfaces refuse.
if (isServerRootResolvedPath(ctx.baseDir, fullPath)) {
return buildMaskedError("That path is the server root — create directories inside it instead.");
}
// The daemon has no /v1/fs/mkdir endpoint, so create the folder via
// its .keep marker — the same /v1/fs/write mechanism nodes.js uses
// for folder creation; mode "create" keeps it create-only (409 when
// the marker already exists).
// adpanel:fs-scope - send the server scope so the node contains the
// operation inside this server's directory (symlink-safe).
const { status, json } = await deps.nodeFsPost(
ctx.node,
"/v1/fs/write",
{ path: safeJoinUnix(fullPath, ".keep"), server: ctx.serverName, content: "", encoding: "utf8", mode: "create" },
120_000
);
if (status === 409) {
return buildSuccess({ server: entry.name, path: dirPath, created: false, alreadyExists: true });
}
if (status !== 200 || !json || !json.ok) {
return buildMaskedError("Failed to create that directory.", {
detail: json?.error || `status ${status}`,
});
}
// adpanel:assistant-activity-warn-only — a recordActivity failure
// must never fail the operation (the panel's own call sites are
// warn-only): a throw here lands in this case's buildMaskedError
// catch and reports a FAILED directory creation after the .keep
// marker was already written.
if (typeof deps.recordActivity === "function") {
try {
deps.recordActivity(entry.name, "file_mkdir", { path: dirPath }, userEmail, userIp);
} catch (err) {
console.warn("[assistant-tools] Failed to record activity:", err?.message || err);
}
}
return buildSuccess({ server: entry.name, path: dirPath, created: true });
} catch (err) {
return buildMaskedError(err?.message || "Invalid path.");
}
}
case "rename_path": {
const { entry, error } = await resolveServerOrError(parsedArgs.server, "files_rename");
if (error) return error;
const source = normalizeRelativePath(parsedArgs.source);
const destination = normalizeRelativePath(parsedArgs.destination);
if (!source || !destination) {
return buildMaskedError("Both source and destination paths are required.");
}
const ctx = await deps.resolveRemoteFsContext(entry.name);
if (!ctx.remote || !ctx.node) {
return buildMaskedError("This server is not attached to a node.");
}
try {
const src = safeJoinUnix(ctx.baseDir, source);
const dest = safeJoinUnix(ctx.baseDir, destination);
if (path.posix.dirname(dest) !== path.posix.dirname(src)) {
return buildMaskedError("cross-directory rename is not supported", {
detail: "The daemon renames paths in place only; it cannot move them between directories.",
});
}
// The daemon's /v1/fs/rename contract is {path, server, newName}: an
// in-place rename of `path` to a new NAME inside the same directory —
// never a move. It runs its Go sanitizeName over newName (slashes are
// stripped), so an absolute path would be flattened into a garbage
// name; send only the basename, normalized panel-side with the same
// rules (utils/daemon-protocol.js).
const newName = daemonRenameNewName(path.posix.basename(dest));
if (!newName) {
return buildMaskedError("Invalid destination name.");
}
// Issue 2 port (mirrors the panel rename routes): refuse no-op and
// root-resolving renames before touching the daemon — renaming over
// the server root is reserved for the dedicated admin server flows.
if (src === dest) {
return buildMaskedError("Source and destination are the same.");
}
if (isServerRootResolvedPath(ctx.baseDir, src) || isServerRootResolvedPath(ctx.baseDir, dest)) {
return buildMaskedError("Refusing to rename the server root.");
}
// Destination pre-check via the daemon's depth-1 list (no single-path
// stat endpoint; racy but cheap) — a failed probe never blocks, the
// daemon's RENAME_NOREPLACE (409) is authoritative. Protects the
// destination against older daemons that still rename with plain
// overwrite semantics.
try {
const list = await deps.nodeFsPost(ctx.node, "/v1/fs/list", { path: path.posix.dirname(dest), depth: 1, server: ctx.serverName }, 60_000);
if (list.status === 200 && list.json?.ok === true && Array.isArray(list.json.entries) && list.json.entries.some((e) => e && e.name === newName)) {
return buildMaskedError("A file with that name already exists.");
}
} catch { }
// adpanel:fs-scope - send the server scope so the node contains the
// operation inside this server's directory (symlink-safe).
const { status, json } = await deps.nodeFsPost(ctx.node, "/v1/fs/rename", { path: src, server: ctx.serverName, newName }, 120_000);
if (status !== 200 || !json || !json.ok) {
if (status === 409 || json?.error === "destination_exists") {
return buildMaskedError("A file with that name already exists.");
}
if (status === 404 || json?.error === "source_not_found") {
return buildMaskedError("That path no longer exists.");
}
return buildMaskedError("Failed to rename that path.", {
detail: json?.error || `status ${status}`,
});
}
// adpanel:assistant-activity-warn-only — a recordActivity failure
// must never fail the operation (the panel's own call sites are
// warn-only): a throw here lands in this case's buildMaskedError
// catch and reports a FAILED rename after the rename already
// succeeded (the source path is already gone).
if (typeof deps.recordActivity === "function") {
try {
deps.recordActivity(entry.name, "file_rename", { src: source, dest: destination }, userEmail, userIp);
} catch (err) {
console.warn("[assistant-tools] Failed to record activity:", err?.message || err);
}
}
return buildSuccess({ server: entry.name, source, destination, renamed: true });
} catch (err) {
return buildMaskedError(err?.message || "Invalid path.");
}
}
case "delete_path": {
const { entry, error } = await resolveServerOrError(parsedArgs.server, "files_delete");
if (error) return error;
const targetPath = normalizeRelativePath(parsedArgs.path);
if (!targetPath) {
return buildMaskedError("A path is required.");
}
const ctx = await deps.resolveRemoteFsContext(entry.name);
if (!ctx.remote || !ctx.node) {
return buildMaskedError("This server is not attached to a node.");
}
try {
const fullPath = safeJoinUnix(ctx.baseDir, targetPath);
// Issue 1 port (mirrors index.js/nodes.js delete paths): the base-dir
// comparison catches "." and other root-resolving inputs that pass
// normalizeRelativePath — against an older daemon (no root guard of
// its own) this was the last panel-side hole for whole-server
// deletion via the assistant.
if (isServerRootResolvedPath(ctx.baseDir, fullPath)) {
return buildMaskedError("Refusing to delete the server root.");
}
const { status, json } = await deps.nodeFsPost(
ctx.node,
"/v1/fs/delete",
// adpanel:fs-scope - send the server scope so the node contains the
// delete inside this server's directory (symlink-safe).
{ path: fullPath, server: ctx.serverName, isDir: !!parsedArgs.isDirectory },
120_000
);
if (status !== 200 || !json || !json.ok) {
return buildMaskedError("Failed to delete that path.", {
detail: json?.error || `status ${status}`,
});
}
// adpanel:assistant-activity-warn-only — a recordActivity failure
// must never fail the operation (the panel's own call sites are
// warn-only): a throw here lands in this case's buildMaskedError
// catch and reports a FAILED delete after the path was already
// removed.
if (typeof deps.recordActivity === "function") {
try {
deps.recordActivity(entry.name, "file_delete", { path: targetPath, isDir: !!parsedArgs.isDirectory }, userEmail, userIp);
} catch (err) {
console.warn("[assistant-tools] Failed to record activity:", err?.message || err);
}
}
return buildSuccess({ server: entry.name, path: targetPath, deleted: true });
} catch (err) {
return buildMaskedError(err?.message || "Invalid path.");
}
}
case "power_server": {
const action = normalizePowerAction(parsedArgs.action);
if (!action) {
return buildMaskedError("Invalid power action.");
}
const requestedServer = String(parsedArgs.server || "").trim();
if (!requestedServer) {
return buildMaskedError("A server name is required.");
}
if (Array.isArray(clientActions)) {
clientActions.push({
type: "assistant_resolve_power_server",
action,
query: requestedServer,
});
}
return buildSuccess({
action,
query: requestedServer,
resolutionRequired: true,
browserActionQueued: true,
});
}
case "power_accessible_servers": {
const action = normalizePowerAction(parsedArgs.action);
if (!action) {
return buildMaskedError("Invalid power action.");
}
if (!accessibleServers.length) {
return buildMaskedError("You do not have access to any servers.");
}
if (Array.isArray(clientActions)) {
clientActions.push({
type: "assistant_power_accessible_servers",
action,
});
}
return buildSuccess({
action,
scope: "accessible",
browserActionQueued: true,
});
}
case "open_server_page": {
const requestedServer = String(parsedArgs.server || "").trim();
const section = String(parsedArgs.section || "").trim();
const allowedSections = new Set([
"console",
"info",
"files",
"activity",
"backups",
"scheduler",
"store",
"resource_stats",
"reinstall",
"ai_help",
]);
if (!requestedServer) {
return buildMaskedError("A server name is required.");
}
if (section && !allowedSections.has(section)) {
return buildMaskedError("Invalid server page section.");
}
if (Array.isArray(clientActions)) {
clientActions.push({
type: "assistant_open_server_page",
query: requestedServer,
section: section || "console",
});
}
return buildSuccess({
query: requestedServer,
section: section || "console",
resolutionRequired: true,
browserActionQueued: true,
});
}
case "open_settings_destination": {
const currentUser = await deps.findUserByEmail(userEmail);
if (!(currentUser && currentUser.admin)) {
return buildMaskedError("Only administrators can open settings tools.");
}
const panel = String(parsedArgs.panel || "").trim();
const action = String(parsedArgs.action || "").trim();
const allowedPanels = new Set([
"preferences",
"customization",
"account",
"security",
"databases",
"nodes",
"templates",
"servers",
"webhooks",
"panelinfo",
]);
const allowedActions = new Set([
"create_user",
"branding",
"login_background",
"alert",
"database_setup",
"pgadmin_setup",
"mongodb_setup",
"captcha",
"maintenance",
"create_node",
"create_template",
"add_webhook",
]);
if (!panel && !action) {
return buildMaskedError("A settings destination is required.");
}
if (panel && !allowedPanels.has(panel)) {
return buildMaskedError("Invalid settings panel.");
}
if (action && !allowedActions.has(action)) {
return buildMaskedError("Invalid settings action.");
}
if (Array.isArray(clientActions)) {
clientActions.push({
type: "assistant_open_settings_destination",
panel,
action,
});
}
return buildSuccess({
panel,
action,
browserActionQueued: true,
});
}
case "open_account_flow": {
const flow = String(parsedArgs.flow || "").trim();
if (![
"change_password",
"change_email",
"change_2fa",
"recover_password",
"recover_email",
"recover_2fa",
].includes(flow)) {
return buildMaskedError("Invalid account flow.");
}
if (Array.isArray(clientActions)) {
clientActions.push({ type: "open_account_flow", flow });
}
return buildSuccess({ flow, browserActionQueued: true });
}
default:
return buildMaskedError(`Unknown tool: ${toolName}`);
}
};
}
module.exports = {
TOOL_DEFINITIONS,
POWER_TOOL_NAMES,
POWER_TOOL_DEFINITIONS,
buildSystemPrompt,
createDashboardAssistantToolRunner,
};