Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+146
View File
@@ -0,0 +1,146 @@
"use strict";
const { isBotReadonlyToolName } = require("../utils/bot-ai-tools");
const { sanitizeNodeStorageName } = require("../utils/server-name");
const { isValidServerAgentChatCursor } = require("../services/server-agent-chat-ownership");
const { findAgentClaim } = require("./job-store");
const { LIVE_SOURCE, UUID_PATTERN } = require("./admission");
const { AGENT_FILE_TOOLS, normalizeAgentFileTool, canAutoApproveAgentFileEdits } = require("./action-proposal");
const { AgentRpcError } = require("./private-rpc");
const { RUN_TIMEOUT_MS } = require("./budgets");
function buildBotServerSummary(entry, perms = null) {
return {
name: entry?.name || null,
displayName: entry?.displayName || entry?.name || null,
status: entry?.status || "unknown",
template: entry?.template || "custom",
permissions: perms || undefined,
};
}
function createLiveAgentServerSummary({ isRemoteEntry, findNodeByIdOrName, getNodeServerPowerState, verifyLocalDockerStopped, withTimeout }) {
return async (req, entry, perms) => {
let observed;
try {
if (isRemoteEntry(entry)) {
const name = sanitizeNodeStorageName(entry.name);
const node = name && await withTimeout(findNodeByIdOrName(entry.nodeId), 5_000, "agent-status-node-lookup-timeout");
if (node) observed = await getNodeServerPowerState(node, name, 5_000, { singleOnly: true });
} else if (/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(entry.name)) {
observed = await verifyLocalDockerStopped(entry.name);
}
} catch { }
req?.aiAgentChatSignal?.throwIfAborted();
if (req?.readAiAgentJobPermissions) await req.readAiAgentJobPermissions(entry.name, entry.id);
const state = observed?.ok === true ? observed.state : null;
const status = state === "online" ? "running" : state || "unknown";
return { ...buildBotServerSummary({ ...entry, status }, perms), statusSource: state ? "runtime" : "unverified" };
};
}
function projectServer(entry) {
return {
name: entry.name, displayName: entry.displayName, legacyId: entry.legacyId,
id: entry.id, bot: entry.bot,
};
}
function createAgentDiagnostics(deps) {
const {
db, featureEnabled, authorizeAgentJobClaim, getAccessibleServerEntriesForAi, applyAiAgentPermClamp,
resolveAiAgentClampAuthorAccess, sanitizeBotToolArgs, runBotAssistantTool, postProcessAiAgentResponse,
executeAiAgentFileOperations, markPlannerItemDoneAfterAgentJobWithRetry, plannerJobSources, readLocalConsole, readLocalConsoleSnapshot, findServer,
isRemoteEntry, applyAutomaticFileEdit, readRuntimeStatus,
} = deps;
return async (operation, args, signal) => {
if (!featureEnabled()) throw new AgentRpcError(503, "agent_disabled");
const { claim } = args || {};
if (!isValidServerAgentChatCursor(claim?.id) || !isValidServerAgentChatCursor(claim?.generation) ||
typeof claim?.token !== "string" || !UUID_PATTERN.test(claim.token)) {
throw new AgentRpcError(400, "agent_invalid_claim");
}
const row = await findAgentClaim(db, claim, operation === "plannerDone");
if (operation === "plannerDone") {
if (!plannerJobSources.has(row.source)) throw new AgentRpcError(403, "agent_wrong_source");
if (row.result_message_id) await markPlannerItemDoneAfterAgentJobWithRetry(row);
return true;
}
const deadline = new Date(row.started_at).getTime() + RUN_TIMEOUT_MS;
let context;
try {
context = await authorizeAgentJobClaim(row, deadline, signal);
const { req, user, entry, serverName } = context;
const permissions = await req.readAiAgentJobPermissions();
signal.throwIfAborted();
if (operation === "verify") return true;
const remote = isRemoteEntry?.(entry) === true;
const automaticFileEdits = remote && canAutoApproveAgentFileEdits(row) && typeof applyAutomaticFileEdit === "function";
if (operation === "autoFileEdit") {
if (!automaticFileEdits) throw new AgentRpcError(403, "agent_automatic_file_edit_denied");
return await applyAutomaticFileEdit({ row, req, user, entry, args, signal });
}
if (operation === "localConsole") {
if (typeof args.target?.name !== "string" || args.target.name.length > 120 || args.target.id == null) {
throw new AgentRpcError(400, "agent_invalid_server");
}
const target = await findServer(args.target.name);
if (!target || String(target.id) !== String(args.target.id) || isRemoteEntry(target)) {
throw new AgentRpcError(409, "agent_console_owner_changed");
}
const targetPerms = await req.readAiAgentJobPermissions(target.name, target.id);
const effective = await applyAiAgentPermClamp(req, targetPerms, target.name);
if (!effective?.console_read) throw new AgentRpcError(403, "agent_authority_revoked");
const lines = await readLocalConsoleSnapshot(target.name, args.limit);
await req.readAiAgentJobPermissions(target.name, target.id);
return lines;
}
if (operation === "fileReads") {
if (typeof args.content !== "string" || args.content.length > 24_000) throw new AgentRpcError(400, "agent_invalid_file_read");
return (await postProcessAiAgentResponse({ content: args.content, serverName, serverId: entry.id, req })).slice(0, 42_000);
}
if (operation === "tool" && (row.source === LIVE_SOURCE || automaticFileEdits)) {
if (AGENT_FILE_TOOLS.some(({ name }) => args.name === name)) {
const fileTool = normalizeAgentFileTool(args.name, args.args);
if (!fileTool) return { ok: false, error: "Give an exact server-relative path for the file or folder." };
if (!permissions?.files_read) return { ok: false, error: "You do not have permission to read files on this server." };
const [result] = await executeAiAgentFileOperations({ operations: [fileTool], serverName, serverId: entry.id, req, structured: true, includeEditVersion: automaticFileEdits });
if (!(await req.readAiAgentFilePermissions())?.files_read) {
return { ok: false, error: "You no longer have permission to read files on this server." };
}
return result;
}
if (typeof args.name !== "string" || !isBotReadonlyToolName(args.name)) {
return { ok: false, error: "That tool is not available. Use the advertised tools and prepare server changes for operator review." };
}
}
const accessible = await getAccessibleServerEntriesForAi(user.email, user.admin);
const capped = accessible.filter((candidate) => candidate.name !== serverName).slice(0, 99);
const servers = [entry, ...capped];
if (operation === "context") {
const clamped = !!req.aiAgentPermClamp;
const visibleServers = clamped ? (await Promise.all(servers.slice(0, 80).map(async (server) => {
const access = await resolveAiAgentClampAuthorAccess(req, server.name);
return access.authorHasAccess ? server.name : null;
}))).filter(Boolean) : [];
const effective = await applyAiAgentPermClamp(req, permissions, serverName);
return { serverName, servers: servers.map(projectServer), visibleServers, permissions: effective,
fileReads: !!effective?.files_read, reviewActions: remote, automaticFileEdits, clamped };
}
if (operation === "tool" && typeof args.name === "string" && isBotReadonlyToolName(args.name)) {
req.readAgentLocalConsole = async (target, limit) => readLocalConsole(claim, projectServer(target), limit, signal);
if (row.source === LIVE_SOURCE && readRuntimeStatus) req.readAgentRuntimeStatus = (target, perms) => readRuntimeStatus(req, target, perms);
return runBotAssistantTool({ req, name: args.name, args: sanitizeBotToolArgs(args.name, args.args), currentServerName: serverName,
accessibleServers: servers, userEmail: user.email, userIp: "", clientActions: [], });
}
throw new AgentRpcError(403, "agent_diagnostic_not_allowed");
} catch (error) {
if (error instanceof AgentRpcError) throw error;
if (error.status === 403 || error.status === 404 || error.status === 409) throw new AgentRpcError(error.status, "agent_authority_revoked");
throw error;
}
};
}
module.exports = { createAgentDiagnostics, buildBotServerSummary, createLiveAgentServerSummary };