Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | 108x 108x 108x 108x 108x 34x 34x 108x 452x 3x 449x 1x 448x 1x 447x 2x 445x 445x 2x 443x 1x 108x 452x 442x 5x 437x 19x 418x 418x 1002x 108x 92x | /*
Copyright (C) 2026 Sber
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Реестр инструментов агента ai-chat, которые дают плагины (DocHub.ai.registerTool).
// Модульный и общий для всех ToolManager браузерного режима: ToolManager ищет тип в реестре
// при каждом обращении, поэтому инструмент, зарегистрированный после создания чата, находится.
// На сервере реестр пуст: DocHub.ai есть только во фронтенде.
import { getLoggerWithTag } from '@global/logger/v2/logger.mjs';
import { ToolInterface } from './types/ToolInterface';
import { ToolTypes } from './types/ToolTypes';
const logger = getLoggerWithTag('pluginToolRegistry');
const TOOL_TYPE_PATTERN = /^[a-z][a-z0-9_]*$/;
const BUILTIN_TOOL_TYPES: string[] = Object.values(ToolTypes);
const pluginTools = new Map<string, ToolInterface>();
const fail = (message: string): never => {
logger.error(() => message);
throw new Error(message);
};
const validatePluginTool = (type: unknown, tool: any): void => {
if (typeof type !== 'string' || !TOOL_TYPE_PATTERN.test(type)) {
fail(`Инструмент ai-chat не зарегистрирован: "type" должен соответствовать ${TOOL_TYPE_PATTERN}, получено ${JSON.stringify(type)}`);
}
if (!tool || typeof tool !== 'object') {
fail(`Инструмент ai-chat "${type}" не зарегистрирован: "tool" должен быть объектом`);
}
if (tool.type !== type) {
fail(`Инструмент ai-chat "${type}" не зарегистрирован: "tool.type" (${JSON.stringify(tool.type)}) не совпадает с "type"`);
}
if (typeof tool.execute !== 'function') {
fail(`Инструмент ai-chat "${type}" не зарегистрирован: "execute" должен быть функцией`);
}
const schema = tool.schema;
if (!schema || typeof schema !== 'object' || typeof schema.name !== 'string' || !schema.name.trim()) {
fail(`Инструмент ai-chat "${type}" не зарегистрирован: "schema" должна быть объектом с непустым "schema.name"`);
}
// Агент ищет запись сценария по имени функции из схемы — оно должно совпадать с type
if (schema.name !== type) {
fail(`Инструмент ai-chat "${type}" не зарегистрирован: "schema.name" (${JSON.stringify(schema.name)}) не совпадает с "type" ("${type}")`);
}
};
// Регистрирует инструмент плагина. Повтор типа (встроенного или уже зарегистрированного) — ошибка.
export const registerPluginTool = (type: string, tool: ToolInterface): void => {
validatePluginTool(type, tool);
if (BUILTIN_TOOL_TYPES.includes(type)) {
fail(`Инструмент ai-chat "${type}" не зарегистрирован: тип совпадает со встроенным инструментом ядра`);
}
if (pluginTools.has(type)) {
fail(`Инструмент ai-chat "${type}" не зарегистрирован: тип уже зарегистрирован другим плагином`);
}
// Копия: подмена execute/schema в объекте плагина после проверки на реестр не влияет
pluginTools.set(type, Object.freeze({ type, schema: structuredClone(tool.schema), execute: tool.execute.bind(tool) }));
logger.debug(() => `Plugin tool registered with type: "${type}"`);
};
export const getPluginTool = (type: string): ToolInterface | undefined => pluginTools.get(type);
// Только для тестов: очищает реестр между тестами.
export const resetPluginToolsForTests = (): void => {
pluginTools.clear();
};
|